提交 06be7f64 编写于 作者: Mr-YX's avatar Mr-YX 提交者: Gitee

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

Signed-off-by: Mr-YX's avatarmr-yx <496043997@qq.com>
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="C:\Program Files\Huawei\DevEco Studio 3.0.0.800\tools\gradle" />
<option name="gradleJvm" value="#JAVA_INTERNAL" />
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/docs.iml" filepath="$PROJECT_DIR$/.idea/docs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
...@@ -38,13 +38,13 @@ ...@@ -38,13 +38,13 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies"> <filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies"> <filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
......
...@@ -65,18 +65,18 @@ The ability assistant enables you to start applications, atomic services, and te ...@@ -65,18 +65,18 @@ The ability assistant enables you to start applications, atomic services, and te
- **dump** - **dump**
Prints ability related information. Prints ability-related information.
| Name | Level-2 Parameter | Description | | Name | Level-2 Parameter | Description |
| ----------------- | -------------------- | ------------------------------------------------------------ | | ----------------- | -------------------- | ------------------------------------------------------------ |
| -h/--help | - | Prints help information. | | -h/--help | - | Prints help information. |
| -a/--all | - | Prints ability information in all missions. | | -a/--all | - | Prints ability information in all missions. |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>NORMAL <br>DEFAULT_STANDARD<br>DEFAULT_SINGLE<br>LAUNCHER | | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER |
| -e/--extension | elementName | Prints extended component information. | | -e/--extension | elementName | Prints extended component information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.| | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. <br/>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**. |
| -d/--data | - | Prints Data ability information. | | -d/--data | - | Prints Data ability information. |
| -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. |
| -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters. <br/>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**. |
**Method** **Method**
......
...@@ -13,7 +13,7 @@ The stage model is designed to make it easier to develop complex applications in ...@@ -13,7 +13,7 @@ The stage model is designed to make it easier to develop complex applications in
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported | Supported | | Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.| | Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
......
...@@ -238,7 +238,7 @@ You can use either of the following methods to connect to a Service ability: ...@@ -238,7 +238,7 @@ You can use either of the following methods to connect to a Service ability:
} }
``` ```
### Connecting to a Remote Service Ability (Applying only to System Applications) ### Connecting to a Remote Service Ability
>**NOTE** >**NOTE**
> >
......
# Ability Development # Ability Development
## When to Use ## When to Use
Unlike the FA model, the [stage model](stage-brief.md) requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop abilities based on the stage model, implement the following logic: Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic:
- Create abilities for an application that involves screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md). - Call abilities. For details, see [Call Development](stage-call.md).
- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). - Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md).
- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). - Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
### Launch Type ### Launch Type
The ability supports three launch types: singleton, multi-instance, and instance-specific. Each launch type, specified by `launchType` in the `module.json` file, specifies the action that can be performed when the ability is started. An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json` file. Depending on the launch type, the action performed when the ability is started differs, as described below.
| Launch Type | Description |Description | | Launch Type | Description |Action |
| ----------- | ------- |---------------- | | ----------- | ------- |---------------- |
| standard | Multi-instance | A new instance is started each time an ability starts.| | standard | Multi-instance | A new instance is started each time an ability starts.|
| singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.| | singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|
By default, the singleton mode is used. The following is an example of the `module.json` file: By default, the singleton mode is used. The following is an example of the `module.json` file:
...@@ -145,9 +145,9 @@ export default class MainAbility extends Ability { ...@@ -145,9 +145,9 @@ export default class MainAbility extends Ability {
} }
``` ```
### Requesting Permissions ### Requesting Permissions
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permissions for calendar access as an example. If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example.
Declare the required permissions in the `module.json` file. Declare the required permission in the `module.json` file.
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -155,7 +155,7 @@ Declare the required permissions in the `module.json` file. ...@@ -155,7 +155,7 @@ Declare the required permissions in the `module.json` file.
} }
] ]
``` ```
Request the permissions from consumers in the form of a dialog box: Request the permission from consumers in the form of a dialog box:
```ts ```ts
let context = this.context let context = this.context
let permissions: Array<string> = ['ohos.permission.READ_CALENDAR'] let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
...@@ -166,11 +166,11 @@ context.requestPermissionsFromUser(permissions).then((data) => { ...@@ -166,11 +166,11 @@ context.requestPermissionsFromUser(permissions).then((data) => {
}) })
``` ```
### Notifying of Environment Changes ### Notifying of Environment Changes
Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by the configuration item in **Settings** or the icon in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md).
For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations. For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations.
The following example shows the implement of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed. The following example shows the implementation of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant' import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
...@@ -184,7 +184,7 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -184,7 +184,7 @@ export default class MyAbilityStage extends AbilityStage {
} }
``` ```
The following example shows the implement of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. The following example shows the implementation of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant' import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
...@@ -205,7 +205,7 @@ export default class MainAbility extends Ability { ...@@ -205,7 +205,7 @@ export default class MainAbility extends Ability {
``` ```
## Starting an Ability ## Starting an Ability
### Available APIs ### Available APIs
The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
**Table 3** AbilityContext APIs **Table 3** AbilityContext APIs
|API|Description| |API|Description|
...@@ -235,9 +235,8 @@ context.startAbility(want).then((data) => { ...@@ -235,9 +235,8 @@ context.startAbility(want).then((data) => {
``` ```
### Starting an Ability on a Remote Device ### Starting an Ability on a Remote Device
This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications. >This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications.
In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows:
```ts ```ts
let context = this.context let context = this.context
var want = { var want = {
...@@ -268,7 +267,7 @@ function getRemoteDeviceId() { ...@@ -268,7 +267,7 @@ function getRemoteDeviceId() {
} }
} }
``` ```
Request the permission `ohos.permission.DISTRIBUTED_DATASYNC ` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions). Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions).
### Starting an Ability with the Specified Page ### Starting an Ability with the Specified Page
If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows: If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows:
......
...@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model. ...@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model.
![stagedesign](figures/stagedesign.png) ![stagedesign](figures/stagedesign.png)
The stage model is designed based on the following considerations: The stage model is designed based on the following considerations:
- **Balance between application capabilities and overall system power consumption** - **Balance between application capabilities and overall system power consumption**
......
...@@ -12,7 +12,8 @@ Basic concepts: ...@@ -12,7 +12,8 @@ Basic concepts:
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. - Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. - Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
...@@ -187,7 +188,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -187,7 +188,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
{ {
"forms": [{ "forms": [{
"name": "widget", "name": "widget",
"description": "This is a service widget.", "description": "This is a widget.",
"src": "./js/widget/pages/index/index", "src": "./js/widget/pages/index/index",
"window": { "window": {
"autoDesignWidth": true, "autoDesignWidth": true,
......
...@@ -39,7 +39,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -39,7 +39,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
``` ```
2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined and overwrite the lifecycle callbacks of the base class. The code sample is as follows: 2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined and override the lifecycle callbacks of the base class. The code sample is as follows:
```js ```js
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc'
......
...@@ -13,6 +13,6 @@ ...@@ -13,6 +13,6 @@
- Vibrator - Vibrator
- [Vibrator Overview](vibrator-overview.md) - [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md) - [Vibrator Development](vibrator-guidelines.md)
- Update Servcie - Update Service
- [Sample Server Overview](sample-server-overview.md) - [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md) - [Sample Server Development](sample-server-guidelines.md)
...@@ -4,7 +4,7 @@ This development guide describes how to use i18n APIs that are not defined in EC ...@@ -4,7 +4,7 @@ This development guide describes how to use i18n APIs that are not defined in EC
## Obtaining System Language and Region Information ## Obtaining System Language and Region Information
APIs are provided to access the system language and region information. You can use APIs provided in the following table to obtain the system language and region information.
### Available APIs ### Available APIs
...@@ -344,14 +344,14 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api ...@@ -344,14 +344,14 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
``` ```
var firstPos = breakIterator.first(); // Sets a BreakIterator object to the first break point, that is, the start position of the text. var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end. var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end.
// Moves a BreakIterator object forward or backward by a certain number of break points. // Move a BreakIterator object forward or backward by a certain number of break points.
// If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward.
// When the object is moved out of the text length range, -1 is returned. // When the object is moved out of the text length range, -1 is returned.
var nextPos = breakIterator.next(-2); var nextPos = breakIterator.next(-2);
var previousPos = breakIterator.previous(); // Moves a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned.
// Moves a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. // Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned.
var followingPos = breakIterator.following(10); var followingPos = breakIterator.following(10);
``` ```
......
...@@ -103,7 +103,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -103,7 +103,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
``` ```
2. Format the date and time.<br> 2. Format the date and time.<br>
Call the **format** method to format a **Date** object. This method returns a string representing the formatting result. Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
``` ```
Date date = new Date(); Date date = new Date();
...@@ -111,7 +111,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -111,7 +111,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
``` ```
3. Format a period.<br> 3. Format a period.<br>
Call the **formatRange** method to format a period. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
``` ```
Date startDate = new Date(); Date startDate = new Date();
...@@ -127,9 +127,9 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -127,9 +127,9 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
``` ```
## Number Formatting ## Formatting Numbers
Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format a number for a specific locale. Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for a specific locale.
### Available APIs ### Available APIs
...@@ -175,7 +175,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format a number fo ...@@ -175,7 +175,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format a number fo
``` ```
## String Sorting ## Sorting Strings
Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting.
...@@ -262,7 +262,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -262,7 +262,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
``` ```
## Formatting Relative Time ## Formatting the Relative Time
Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the relative time for a specific locale. Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the relative time for a specific locale.
......
...@@ -56,7 +56,7 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to ...@@ -56,7 +56,7 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
3. Define the callback `OnSurfaceCreated`. During the creation of a `Surface`, the callback is used to initialize the rendering environment, for example, the `Skia` rendering environment, and write the content to be displayed to `NativeWindow`. 3. Define the callback `OnSurfaceCreated`. During the creation of a `Surface`, the callback is used to initialize the rendering environment, for example, the `Skia` rendering environment, and write the content to be displayed to `NativeWindow`.
```c++ ```c++
void OnSufaceCreatedCB(NativeXComponent* component, void* window) { void OnSurfaceCreatedCB(NativeXComponent* component, void* window) {
// Obtain the width and height of the native window. // Obtain the width and height of the native window.
uint64_t width_ = 0, height_ = 0; uint64_t width_ = 0, height_ = 0;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_); OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
...@@ -89,8 +89,8 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to ...@@ -89,8 +89,8 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
// Create Skia Canvas and write the content to the native window. // Create Skia Canvas and write the content to the native window.
... ...
// After the write operation is complete, flush the buffer by using OH_NativeWindwo_NativeWindowFlushBuffer so that the data is displayed on the screen. // After the write operation is complete, flush the buffer by using OH_NativeWindow_NativeWindowFlushBuffer so that the data is displayed on the screen.
Regoin region{nullptr, 0}; Region region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region) OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
} }
``` ```
...@@ -99,9 +99,9 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to ...@@ -99,9 +99,9 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
```c++ ```c++
OH_NativeXComponent_Callback &callback_; OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB; callback_->OnSurfaceCreated = OnSurfaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB; callback_->OnSurfaceChanged = OnSurfaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB; callback_->OnSurfaceDestoryed = OnSurfaceDestoryedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB; callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_) OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
``` ```
...@@ -11,4 +11,4 @@ ...@@ -11,4 +11,4 @@
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [Resource File Categories](basic-resource-file-categories.md) - [Resource File Categories](basic-resource-file-categories.md)
- [SysCap](syscap.md) - [SysCap](syscap.md)
- [HarmonyAppProvision Configuration File](app-provision-structure.md)
# HarmonyAppProvision Configuration File
The **HarmonyAppProvision** configuration file (also called profile) is the file where you declare permission and signature information for your application.
## Configuration File Internal Structure
The **HarmonyAppProvision** file consists of several parts, which are described in the table below.
**Table 1** Configuration file internal structure
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- |
| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No |
| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No|
| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No|
| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) and **release** (for application release). The recommended value is **debug**.| String | Yes | No|
| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No|
| validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No |
| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No |
| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | No |
| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | No |
| debug-info | Additional debug information. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | No |
An example of the **HarmonyAppProvision** file is as follows:
```json
{
"version-code": 1,
"version-name": "1.0.0",
"uuid": "string",
"type": "debug",
"validity": {
"not-before": 1586422743,
"not-after": 1617958743
},
"bundle-info" : {
"developer-id": "OpenHarmony",
"development-certificate": "Base64 string",
"distribution-certificate": "Base64 string",
"bundle-name": "com.OpenHarmony.app.test",
"apl": "normal",
"app-feature": "hos_normal_app"
},
"acls": {
"allowed-acls": ["string"]
},
"permissions": {
"restricted-permissions": ["string"]
},
"debug-info" : {
"device-id-type": "udid",
"device-ids": ["string"]
},
"issuer": "OpenHarmony"
}
```
### Internal Structure of the validity Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ---------- | ------------------------------- | ------- | ------- | --------- |
| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No |
| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No |
### Internal Structure of the bundle-info Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | -------- | --------- |
| developer-id | Unique ID of the developer.| String | Yes | No |
| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No |
| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise | No |
| bundle-name | Bundle name of the application.| String | Yes | No |
| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No |
| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes | No |
### Internal structure of the acls Object
The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 4** Internal structure of the acls object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No |
### Internal Structure of the permissions Object
The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 5** Internal structure of the permissions object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No | No |
### Internal Structure of the debug-info Object
The **debug-info** object contains debug information of your application, mainly device management and control information.
**Table 6** Internal structure of the debug-info object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No |
| device-ids | IDs of devices on which your application can be debugged.| String array | No | No |
# App Account Management # App Account Management
Provides app account management, including adding, deleting, querying, modifying, and authorizing app accounts, writing data to disks, and synchronizing data.
> **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -20,13 +22,14 @@ Creates an **AppAccountManager** instance. ...@@ -20,13 +22,14 @@ Creates an **AppAccountManager** instance.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Return Value** **Return Value**
| Type | Description |
| ----------------- | ------------ | | Type | Description |
| AppAccountManager | **AppAccountManager** instance created. | | ----------------- | ------------ |
| AppAccountManager | **AppAccountManager** instance created.|
**Example** **Example**
```js ```js
var appAccountManager = account.createAppAccountManager(); const appAccountManager = account_appAccount.createAppAccountManager();
``` ```
## AppAccountManager ## AppAccountManager
...@@ -37,16 +40,16 @@ Provides methods to manage app accounts. ...@@ -37,16 +40,16 @@ Provides methods to manage app accounts.
addAccount(name: string, callback: AsyncCallback&lt;void&gt;): void addAccount(name: string, callback: AsyncCallback&lt;void&gt;): void
Adds an app account to the account management service. This method uses an asynchronous callback to return the result. Adds an app account to the **AppAccountManager** service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------------- | | -------- | ------------------------- | ---- | -------------------- |
| name | string | Yes | Name of the app account to add. | | name | string | Yes | Name of the app account to add. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is added. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is added.|
**Example** **Example**
...@@ -61,17 +64,17 @@ Adds an app account to the account management service. This method uses an async ...@@ -61,17 +64,17 @@ Adds an app account to the account management service. This method uses an async
addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void
Adds an app account and its additional information to the account management service. This method uses an asynchronous callback to return the result. Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- | | --------- | ------------------------- | ---- | ---------------------------------------- |
| name | string | Yes | Name of the app account to add. | | name | string | Yes | Name of the app account to add. |
| extraInfo | string | Yes | Additional information (for example, token) of the app account to add. The additional information cannot contain sensitive information about the app account. | | extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account and its additional information are added. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account name and additional information are added. |
**Example** **Example**
...@@ -86,24 +89,24 @@ Adds an app account and its additional information to the account management ser ...@@ -86,24 +89,24 @@ Adds an app account and its additional information to the account management ser
### addAccount ### addAccount
addAccount(name: string, extraInfo?: string): Promise&lt;void&gt; addAccount(name: string, extraInfo: string): Promise&lt;void&gt;
Adds an app account and its additional information to the account management service. This method uses a promise to return the result. Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | -------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the app account to add. | | name | string | Yes | Name of the app account to add. |
| extraInfo | string | Yes | Additional information of the app account to add. The additional information cannot contain sensitive information about the app account. | | extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -120,18 +123,18 @@ Adds an app account and its additional information to the account management ser ...@@ -120,18 +123,18 @@ Adds an app account and its additional information to the account management ser
addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
Implicitly adds an app account based on the specified account owner, authentication type, and options. This method uses an asynchronous callback to return the result. Implicitly adds an app account based on the specified account owner, authentication type, and options. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------- | ---- | --------------- | | -------- | --------------------- | ---- | ----------------------- |
| owner | string | Yes | Bundle name of the app account to add. | | owner | string | Yes | Owner of the app account to add. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type of the app account to add. | | authType | string | Yes | Authentication type of the app account to add. The authentication type is customized. |
| options | {[key: string]: any} | Yes | Options for the authentication. | | options | {[key: string]: any} | Yes | Authentication options, which can be set as required.|
| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result. | | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result. |
**Example** **Example**
...@@ -161,16 +164,16 @@ Implicitly adds an app account based on the specified account owner, authenticat ...@@ -161,16 +164,16 @@ Implicitly adds an app account based on the specified account owner, authenticat
deleteAccount(name: string, callback: AsyncCallback&lt;void&gt;): void deleteAccount(name: string, callback: AsyncCallback&lt;void&gt;): void
Deletes an app account from the account management service. This method uses an asynchronous callback to return the result. Deletes an app account from the **AppAccountManager** service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------------- | | -------- | ------------------------- | ---- | ---------------- |
| name | string | Yes | Name of the app account to delete. | | name | string | Yes | Name of the app account to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is deleted. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is deleted.|
**Example** **Example**
...@@ -185,21 +188,21 @@ Deletes an app account from the account management service. This method uses an ...@@ -185,21 +188,21 @@ Deletes an app account from the account management service. This method uses an
deleteAccount(name: string): Promise&lt;void&gt; deleteAccount(name: string): Promise&lt;void&gt;
Deletes an app account from the account management service. This method uses a promise to return the result. Deletes an app account from the **AppAccountManager** service. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ----------- |
| name | string | Yes | Name of the app account to delete. | | name | string | Yes | Name of the app account to delete.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -216,17 +219,17 @@ Deletes an app account from the account management service. This method uses a p ...@@ -216,17 +219,17 @@ Deletes an app account from the account management service. This method uses a p
disableAppAccess(name: string, bundleName: string, callback: AsyncCallback&lt;void&gt;): void disableAppAccess(name: string, bundleName: string, callback: AsyncCallback&lt;void&gt;): void
Disables an app account from accessing an application with the given bundle name. This method uses an asynchronous callback to return the result. Disables an app account from accessing an app with the given bundle name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------- | ---- | ------------------------------- | | ---------- | ------------------------- | ---- | --------------------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of an app. | | bundleName | string | Yes | Bundle name of the app. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -241,22 +244,22 @@ Disables an app account from accessing an application with the given bundle name ...@@ -241,22 +244,22 @@ Disables an app account from accessing an application with the given bundle name
disableAppAccess(name: string, bundleName: string): Promise&lt;void&gt; disableAppAccess(name: string, bundleName: string): Promise&lt;void&gt;
Disables an app account from accessing an application with the given bundle name. This method uses a promise to return the result. Disables an app account from accessing an app with the given bundle name. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ----------------- | | ---------- | ------ | ---- | ---------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account.|
| bundleName | string | Yes | Bundle name of an app. | | bundleName | string | Yes | Bundle name of the app. |
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -273,17 +276,17 @@ Disables an app account from accessing an application with the given bundle name ...@@ -273,17 +276,17 @@ Disables an app account from accessing an application with the given bundle name
enableAppAccess(name: string, bundleName: string, callback: AsyncCallback&lt;void&gt;): void enableAppAccess(name: string, bundleName: string, callback: AsyncCallback&lt;void&gt;): void
Enables an app account to access an application with the given bundle name. This method uses an asynchronous callback to return the result. Enables an app account to access an app with the given bundle name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------- | ---- | ------------------------------- | | ---------- | ------------------------- | ---- | --------------------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of an app. | | bundleName | string | Yes | Bundle name of the app. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -298,22 +301,22 @@ Enables an app account to access an application with the given bundle name. This ...@@ -298,22 +301,22 @@ Enables an app account to access an application with the given bundle name. This
enableAppAccess(name: string, bundleName: string): Promise&lt;void&gt; enableAppAccess(name: string, bundleName: string): Promise&lt;void&gt;
Enables an app account to access an application with the given bundle name. This method uses a promise to return the result. Enables an app account to access an app with the given bundle name. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | --------- | | ---------- | ------ | ---- | --------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of an app. | | bundleName | string | Yes | Bundle name of the app.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -329,7 +332,7 @@ Enables an app account to access an application with the given bundle name. This ...@@ -329,7 +332,7 @@ Enables an app account to access an application with the given bundle name. This
checkAppAccountSyncEnable(name: string, callback: AsyncCallback&lt;boolean&gt;): void checkAppAccountSyncEnable(name: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether an app account allows application data synchronization. This method uses an asynchronous callback to return the result. Checks whether an app account allows app data synchronization. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications)
...@@ -337,10 +340,10 @@ Checks whether an app account allows application data synchronization. This meth ...@@ -337,10 +340,10 @@ Checks whether an app account allows application data synchronization. This meth
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------- | | -------- | ---------------------------- | ---- | --------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return whether the app account allows application data synchronization. | | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -356,7 +359,7 @@ Checks whether an app account allows application data synchronization. This meth ...@@ -356,7 +359,7 @@ Checks whether an app account allows application data synchronization. This meth
checkAppAccountSyncEnable(name: string): Promise&lt;boolean&gt; checkAppAccountSyncEnable(name: string): Promise&lt;boolean&gt;
Checks whether an app account allows application data synchronization. This method uses a promise to return the result. Checks whether an app account allows app data synchronization. This API uses a promise to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications)
...@@ -364,15 +367,15 @@ Checks whether an app account allows application data synchronization. This meth ...@@ -364,15 +367,15 @@ Checks whether an app account allows application data synchronization. This meth
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :--------------------- | :-------------------- | | :--------------------- | :-------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. | | Promise&lt;boolean&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -387,20 +390,20 @@ Checks whether an app account allows application data synchronization. This meth ...@@ -387,20 +390,20 @@ Checks whether an app account allows application data synchronization. This meth
### setAccountCredential ### setAccountCredential
setAccountCredential(name: string, credentialType: string, credential: string, callback: AsyncCallback&lt;void&gt;): void setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback&lt;void&gt;): void
Sets a credential for an app account. This method uses an asynchronous callback to return the result. Sets a credential for an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ---- | -------------- | | -------------- | ------------------------- | ---- | ------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to set. | | credentialType | string | Yes | Type of the credential to set. |
| credential | string | Yes | Credential to set. | | credential | string | Yes | Credential to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when a credential is set for the specified app account. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -415,23 +418,23 @@ Sets a credential for an app account. This method uses an asynchronous callback ...@@ -415,23 +418,23 @@ Sets a credential for an app account. This method uses an asynchronous callback
setAccountCredential(name: string, credentialType: string, credential: string): Promise&lt;void&gt; setAccountCredential(name: string, credentialType: string, credential: string): Promise&lt;void&gt;
Sets a credential for an app account. This method uses a promise to return the result asynchronously. Sets a credential for an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to set. | | credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential to set. | | credential | string | Yes | Credential to set. |
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -448,17 +451,17 @@ Sets a credential for an app account. This method uses a promise to return the r ...@@ -448,17 +451,17 @@ Sets a credential for an app account. This method uses a promise to return the r
setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void
Sets additional information for an app account. This method uses an asynchronous callback to return the result. Sets additional information for an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------- | | --------- | ------------------------- | ---- | --------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| extraInfo | string | Yes | Additional information to set. | | extraInfo | string | Yes | Additional information to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when additional information is set for the specified app account. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -473,22 +476,22 @@ Sets additional information for an app account. This method uses an asynchronous ...@@ -473,22 +476,22 @@ Sets additional information for an app account. This method uses an asynchronous
setAccountExtraInfo(name: string, extraInfo: string): Promise&lt;void&gt; setAccountExtraInfo(name: string, extraInfo: string): Promise&lt;void&gt;
Sets additional information for an app account. This method uses a promise to return the result asynchronously. Sets additional information for an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | --------- | | --------- | ------ | ---- | --------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| extraInfo | string | Yes | Additional information to set. | | extraInfo | string | Yes | Additional information to set.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -505,7 +508,7 @@ Sets additional information for an app account. This method uses a promise to re ...@@ -505,7 +508,7 @@ Sets additional information for an app account. This method uses a promise to re
setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback&lt;void&gt;): void setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback&lt;void&gt;): void
Sets whether to enable application data synchronization for an app account. This method uses an asynchronous callback to return the result. Sets whether to enable app data synchronization for an app account. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications)
...@@ -513,11 +516,11 @@ Sets whether to enable application data synchronization for an app account. This ...@@ -513,11 +516,11 @@ Sets whether to enable application data synchronization for an app account. This
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------- | | -------- | ------------------------- | ---- | ------------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| isEnable | boolean | Yes | Whether to enable app data synchronization. | | isEnable | boolean | Yes | Whether to enable app data synchronization. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when application data synchronization is enabled or disabled for the app account. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when app data synchronization is enabled or disabled for the app account.|
**Example** **Example**
...@@ -532,7 +535,7 @@ Sets whether to enable application data synchronization for an app account. This ...@@ -532,7 +535,7 @@ Sets whether to enable application data synchronization for an app account. This
setAppAccountSyncEnable(name: string, isEnable: boolean): Promise&lt;void&gt; setAppAccountSyncEnable(name: string, isEnable: boolean): Promise&lt;void&gt;
Sets whether to enable application data synchronization for an app account. This method uses a promise to return the result asynchronously. Sets whether to enable app data synchronization for an app account. This API uses a promise to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications)
...@@ -540,16 +543,16 @@ Sets whether to enable application data synchronization for an app account. This ...@@ -540,16 +543,16 @@ Sets whether to enable application data synchronization for an app account. This
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------- | ---- | ----------- | | -------- | ------- | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| isEnable | boolean | Yes | Whether to enable app data synchronization. | | isEnable | boolean | Yes | Whether to enable app data synchronization.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -566,18 +569,18 @@ Sets whether to enable application data synchronization for an app account. This ...@@ -566,18 +569,18 @@ Sets whether to enable application data synchronization for an app account. This
setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback&lt;void&gt;): void setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback&lt;void&gt;): void
Sets data to be associated with an app account. This method uses an asynchronous callback to return the result. Sets data to be associated with an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------------- | | -------- | ------------------------- | ---- | ----------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to set. The private key can be customized. | | key | string | Yes | Key of the data to set. The private key can be customized.|
| value | string | Yes | Value of the data to be set. | | value | string | Yes | Value of the data to be set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the data associated with the specified app account is set. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the data associated with the specified app account is set.|
**Example** **Example**
...@@ -591,23 +594,23 @@ Sets data to be associated with an app account. This method uses an asynchronous ...@@ -591,23 +594,23 @@ Sets data to be associated with an app account. This method uses an asynchronous
setAssociatedData(name: string, key: string, value: string): Promise&lt;void&gt; setAssociatedData(name: string, key: string, value: string): Promise&lt;void&gt;
Sets data to be associated with an app account. This method uses a promise to return the result asynchronously. Sets data to be associated with an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------- | | ----- | ------ | ---- | ----------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to set. The private key can be customized. | | key | string | Yes | Key of the data to set. The private key can be customized.|
| value | string | Yes | Value of the data to be set. | | value | string | Yes | Value of the data to be set. |
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -624,17 +627,17 @@ Sets data to be associated with an app account. This method uses a promise to re ...@@ -624,17 +627,17 @@ Sets data to be associated with an app account. This method uses a promise to re
getAccountCredential(name: string, credentialType: string, callback: AsyncCallback&lt;string&gt;): void getAccountCredential(name: string, credentialType: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the credential of an app account. This method uses an asynchronous callback to return the result. Obtains the credentials (such as the digital password, face image, and PIN) of an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | -------------- | | -------------- | --------------------------- | ---- | -------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to obtain. | | credentialType | string | Yes | Type of the credential to obtain.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the credential of the specified app account. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the credential obtained.|
**Example** **Example**
...@@ -650,22 +653,22 @@ Obtains the credential of an app account. This method uses an asynchronous callb ...@@ -650,22 +653,22 @@ Obtains the credential of an app account. This method uses an asynchronous callb
getAccountCredential(name: string, credentialType: string): Promise&lt;string&gt; getAccountCredential(name: string, credentialType: string): Promise&lt;string&gt;
Obtains the credential of an app account. This method uses a promise to return the result asynchronously. Obtains the credential of an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to obtain. | | credentialType | string | Yes | Type of the credential to obtain.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
| Promise&lt;string&gt; | Promise used to return the result. | | Promise&lt;string&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -682,16 +685,16 @@ Obtains the credential of an app account. This method uses a promise to return t ...@@ -682,16 +685,16 @@ Obtains the credential of an app account. This method uses a promise to return t
getAccountExtraInfo(name: string, callback: AsyncCallback&lt;string&gt;): void getAccountExtraInfo(name: string, callback: AsyncCallback&lt;string&gt;): void
Obtains additional information of an app account. This method uses an asynchronous callback to return the result. Obtains additional information (information that can be converted into the string type) about an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ---------------- | | -------- | --------------------------- | ---- | --------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the additional information of the specified app account. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the additional information of the specified app account.|
**Example** **Example**
...@@ -707,21 +710,21 @@ Obtains additional information of an app account. This method uses an asynchrono ...@@ -707,21 +710,21 @@ Obtains additional information of an app account. This method uses an asynchrono
getAccountExtraInfo(name: string): Promise&lt;string&gt; getAccountExtraInfo(name: string): Promise&lt;string&gt;
Obtains additional information of an app account. This method uses a promise to return the result asynchronously. Obtains additional information of an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
| Promise&lt;string&gt; | Promise used to return the result. | | Promise&lt;string&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -738,17 +741,17 @@ Obtains additional information of an app account. This method uses a promise to ...@@ -738,17 +741,17 @@ Obtains additional information of an app account. This method uses a promise to
getAssociatedData(name: string, key: string, callback: AsyncCallback&lt;string&gt;): void getAssociatedData(name: string, key: string, callback: AsyncCallback&lt;string&gt;): void
Obtains data associated with an app account. This method uses an asynchronous callback to return the result. Obtains data associated with an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ----------------- | | -------- | --------------------------- | ---- | ----------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to obtain. | | key | string | Yes | Key of the data to obtain. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the data associated with the specified app account. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the data associated with the specified app account.|
**Example** **Example**
...@@ -764,22 +767,22 @@ Obtains data associated with an app account. This method uses an asynchronous ca ...@@ -764,22 +767,22 @@ Obtains data associated with an app account. This method uses an asynchronous ca
getAssociatedData(name: string, key: string): Promise&lt;string&gt; getAssociatedData(name: string, key: string): Promise&lt;string&gt;
Obtains data associated with an app account. This method uses a promise to return the result asynchronously. Obtains data associated with an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------- | | ---- | ------ | ---- | --------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to obtain. | | key | string | Yes | Key of the data to obtain.|
**Return Value** **Return Value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
| Promise&lt;string&gt; | Promise used to return the result. | | Promise&lt;string&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -796,7 +799,7 @@ Obtains data associated with an app account. This method uses a promise to retur ...@@ -796,7 +799,7 @@ Obtains data associated with an app account. This method uses a promise to retur
getAllAccessibleAccounts(callback: AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt;): void getAllAccessibleAccounts(callback: AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt;): void
Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications)
...@@ -804,9 +807,9 @@ Obtains information about all accessible app accounts. This method uses an async ...@@ -804,9 +807,9 @@ Obtains information about all accessible app accounts. This method uses an async
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------- | | -------- | ---------------------------------------- | ---- | --------- |
| callback | AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt; | Yes | Callback invoked to return information about all accessible app accounts. | | callback | AsyncCallback&lt;Array&lt;[AppAccountInfo](#appaccountinfo)&gt;&gt; | Yes | Callback invoked to return information about all accessible app accounts.|
**Example** **Example**
...@@ -822,7 +825,7 @@ Obtains information about all accessible app accounts. This method uses an async ...@@ -822,7 +825,7 @@ Obtains information about all accessible app accounts. This method uses an async
getAllAccessibleAccounts(): Promise&lt;Array&lt;AppAccountInfo&gt;&gt; getAllAccessibleAccounts(): Promise&lt;Array&lt;AppAccountInfo&gt;&gt;
Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. Obtains information about all accessible app accounts. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications)
...@@ -830,9 +833,9 @@ Obtains information about all accessible app accounts. This method uses an async ...@@ -830,9 +833,9 @@ Obtains information about all accessible app accounts. This method uses an async
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ---------------------------------------- | --------------------- | | ---------------------------------------- | --------------------- |
| Promise&lt;Array&lt;AppAccountInfo&gt;&gt; | Promise used to return the result. | | Promise&lt;Array&lt;[AppAccountInfo](#appaccountinfo)&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -849,7 +852,7 @@ Obtains information about all accessible app accounts. This method uses an async ...@@ -849,7 +852,7 @@ Obtains information about all accessible app accounts. This method uses an async
getAllAccounts(owner: string, callback: AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt;): void getAllAccounts(owner: string, callback: AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt;): void
Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. Obtains information about all app accounts of the specified app. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications)
...@@ -857,10 +860,10 @@ Obtains information about all app accounts of the specified app. This method use ...@@ -857,10 +860,10 @@ Obtains information about all app accounts of the specified app. This method use
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------- | | -------- | ---------------------------------------- | ---- | --------- |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| callback | AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt; | Yes | Callback invoked to return information about all accessible app accounts. | | callback | AsyncCallback&lt;Array&lt;[AppAccountInfo](#appaccountinfo)&gt;&gt; | Yes | Callback invoked to return information about all accessible app accounts.|
**Example** **Example**
...@@ -877,7 +880,7 @@ Obtains information about all app accounts of the specified app. This method use ...@@ -877,7 +880,7 @@ Obtains information about all app accounts of the specified app. This method use
getAllAccounts(owner: string): Promise&lt;Array&lt;AppAccountInfo&gt;&gt; getAllAccounts(owner: string): Promise&lt;Array&lt;AppAccountInfo&gt;&gt;
Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. Obtains information about all app accounts of the specified app. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications)
...@@ -885,15 +888,15 @@ Obtains information about all app accounts of the specified app. This method use ...@@ -885,15 +888,15 @@ Obtains information about all app accounts of the specified app. This method use
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- | | ----- | ------ | ---- | ------ |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ---------------------------------------- | --------------------- | | ---------------------------------------- | --------------------- |
| Promise&lt;Array&lt;AppAccountInfo&gt;&gt; | Promise used to return the result. | | Promise&lt;Array&lt;[AppAccountInfo](#appaccountinfo)&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -911,17 +914,17 @@ Obtains information about all app accounts of the specified app. This method use ...@@ -911,17 +914,17 @@ Obtains information about all app accounts of the specified app. This method use
on(type: 'change', owners: Array&lt;string&gt;, callback: Callback&lt;Array&lt;AppAccountInfo&gt;&gt;): void on(type: 'change', owners: Array&lt;string&gt;, callback: Callback&lt;Array&lt;AppAccountInfo&gt;&gt;): void
Subscribes to the account change event of the specified account owners. This method uses an asynchronous callback to return the result. Subscribes to the account change events of the specified account owners. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------ | | -------- | ---------------------------------------- | ---- | ------------------------------ |
| type | 'change' | Yes | Type of the event to subscribe to. The subscriber will receive a notification when the account owners update their accounts. | | type | 'change' | Yes | Account change events to subscribe to. The subscriber will receive a notification when the account owners update their accounts.|
| owners | Array&lt;string&gt; | Yes | Owners of the accounts. | | owners | Array&lt;string&gt; | Yes | Account owners. |
| callback | Callback&lt;Array&lt;AppAccountInfo&gt;&gt; | Yes | Callback invoked to return the account change. | | callback | Callback&lt;Array&lt;[AppAccountInfo](#appaccountinfo)&gt;&gt; | Yes | Callback invoked to return the account changes. |
**Example** **Example**
...@@ -942,16 +945,16 @@ Subscribes to the account change event of the specified account owners. This met ...@@ -942,16 +945,16 @@ Subscribes to the account change event of the specified account owners. This met
off(type: 'change', callback?: Callback<Array\<AppAccountInfo>>): void off(type: 'change', callback?: Callback<Array\<AppAccountInfo>>): void
Unsubscribes from the account change event. This method uses an asynchronous callback to return the result. Unsubscribes from the account change events. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ------------ | | -------- | -------------------------------- | ---- | ------------ |
| type | 'change' | Yes | Account change event to unsubscribe from. | | type | 'change' | Yes | Account change events to unsubscribe from. |
| callback | Callback<Array\<AppAccountInfo>> | No | Callback used to report the account change. | | callback | Callback<Array\<[AppAccountInfo](#appaccountinfo)>> | No | Callback used to report the account changes.|
**Example** **Example**
...@@ -975,19 +978,19 @@ Unsubscribes from the account change event. This method uses an asynchronous cal ...@@ -975,19 +978,19 @@ Unsubscribes from the account change event. This method uses an asynchronous cal
authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
Authenticates an app account to obtain the Open Authorization (OAuth) access token. This method uses an asynchronous callback to return the result. Authenticates an app account to obtain the Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------- | ---- | --------------- | | -------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the app account to authenticate. | | name | string | Yes | Name of the app account to authenticate. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| options | {[key: string]: any} | Yes | Options for the authentication. | | options | {[key: string]: any} | Yes | Options for the authentication. |
| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result. | | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.|
**Example** **Example**
...@@ -1017,18 +1020,18 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok ...@@ -1017,18 +1020,18 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok
getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback&lt;string&gt;): void getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the OAuth access token of an app account based on the specified authentication type. This method uses an asynchronous callback to return the result. Obtains the OAuth token of an app account based on the specified authentication type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ----------- | | -------- | --------------------------- | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1044,23 +1047,23 @@ Obtains the OAuth access token of an app account based on the specified authenti ...@@ -1044,23 +1047,23 @@ Obtains the OAuth access token of an app account based on the specified authenti
getOAuthToken(name: string, owner: string, authType: string): Promise&lt;string&gt; getOAuthToken(name: string, owner: string, authType: string): Promise&lt;string&gt;
Obtains the OAuth access token of an app account based on the specified authentication type. This method uses a promise to return the result. Obtains the OAuth token of an app account based on the specified authentication type. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- | | -------- | ------ | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| --------------------- | --------------------- | | --------------------- | --------------------- |
| Promise&lt;string&gt; | Promise used to return the result. | | Promise&lt;string&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1077,18 +1080,18 @@ Obtains the OAuth access token of an app account based on the specified authenti ...@@ -1077,18 +1080,18 @@ Obtains the OAuth access token of an app account based on the specified authenti
setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback&lt;void&gt;): void setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback&lt;void&gt;): void
Sets an OAuth access token for an app account. This method uses an asynchronous callback to return the result. Sets an OAuth token for an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | -------- | | -------- | ------------------------- | ---- | -------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account.|
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| token | string | Yes | OAuth access token to set. | | token | string | Yes | OAuth token to set.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Example** **Example**
...@@ -1103,23 +1106,23 @@ Sets an OAuth access token for an app account. This method uses an asynchronous ...@@ -1103,23 +1106,23 @@ Sets an OAuth access token for an app account. This method uses an asynchronous
setOAuthToken(name: string, authType: string, token: string): Promise&lt;void&gt; setOAuthToken(name: string, authType: string, token: string): Promise&lt;void&gt;
Sets an OAuth access token for an app account. This method uses a promise to return the result. Sets an OAuth token for an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ---- | -------- | | -------- | ------ | ---- | -------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account.|
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| token | string | Yes | OAuth access token to set. | | token | string | Yes | OAuth token to set.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1136,19 +1139,19 @@ Sets an OAuth access token for an app account. This method uses a promise to ret ...@@ -1136,19 +1139,19 @@ Sets an OAuth access token for an app account. This method uses a promise to ret
deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback&lt;void&gt;): void deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback&lt;void&gt;): void
Deletes the specified OAuth access token for an app account. This method uses an asynchronous callback to return the result. Deletes the specified OAuth token for an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------ | | -------- | ------------------------- | ---- | ------------ |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| token | string | Yes | OAuth access token to delete. | | token | string | Yes | OAuth token to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1163,24 +1166,24 @@ Deletes the specified OAuth access token for an app account. This method uses an ...@@ -1163,24 +1166,24 @@ Deletes the specified OAuth access token for an app account. This method uses an
deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise&lt;void&gt; deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise&lt;void&gt;
Deletes the specified OAuth access token for an app account. This method uses a promise to return the result. Deletes the specified OAuth token for an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------ | | -------- | ------ | ---- | ------------ |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| token | string | Yes | OAuth access token to delete. | | token | string | Yes | OAuth token to delete.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1197,19 +1200,19 @@ Deletes the specified OAuth access token for an app account. This method uses a ...@@ -1197,19 +1200,19 @@ Deletes the specified OAuth access token for an app account. This method uses a
setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback&lt;void&gt;): void setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback&lt;void&gt;): void
Sets the visibility of an OAuth access token to the specified app. This method uses an asynchronous callback to return the result. Sets the visibility of an OAuth token to an app. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------- | ---- | ------------ | | ---------- | ------------------------- | ---- | ------------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app. |
| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | | isVisible | boolean | Yes | Whether the OAuth token is visible to the app. The value **true** means visible, and the value **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1224,24 +1227,24 @@ Sets the visibility of an OAuth access token to the specified app. This method u ...@@ -1224,24 +1227,24 @@ Sets the visibility of an OAuth access token to the specified app. This method u
setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise&lt;void&gt; setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise&lt;void&gt;
Sets the visibility of an OAuth access token to the specified app. This method uses a promise to return the result. Sets the visibility of an OAuth token to an app. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------- | ---- | ------------ | | ---------- | ------- | ---- | ------------ |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app.|
| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | | isVisible | boolean | Yes | Whether the OAuth token is visible to the app. |
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1258,18 +1261,18 @@ Sets the visibility of an OAuth access token to the specified app. This method u ...@@ -1258,18 +1261,18 @@ Sets the visibility of an OAuth access token to the specified app. This method u
checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether an OAuth token is visible to the specified app. This method uses an asynchronous callback to return the result. Checks whether an OAuth token is visible to an app. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ---------------------------- | ---- | ------------- | | ---------- | ---------------------------- | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app.|
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1285,23 +1288,23 @@ Checks whether an OAuth token is visible to the specified app. This method uses ...@@ -1285,23 +1288,23 @@ Checks whether an OAuth token is visible to the specified app. This method uses
checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise&lt;boolean&gt; checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise&lt;boolean&gt;
Checks whether an OAuth token is visible to the specified app. This method uses a promise to return the result. Checks whether an OAuth token is visible to an app. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------- | | ---------- | ------ | ---- | ------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ---------------------- | --------------------- | | ---------------------- | --------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. | | Promise&lt;boolean&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1318,17 +1321,17 @@ Checks whether an OAuth token is visible to the specified app. This method uses ...@@ -1318,17 +1321,17 @@ Checks whether an OAuth token is visible to the specified app. This method uses
getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback&lt;Array&lt;OAuthTokenInfo&gt;&gt;): void getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback&lt;Array&lt;OAuthTokenInfo&gt;&gt;): void
Obtains information about all OAuth access tokens of an app account visible to the specified app. This method uses an asynchronous callback to return the result. Obtains all OAuth tokens visible to the caller for an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------- | | -------- | ---------------------------------------- | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| callback | AsyncCallback&lt;Array&lt;OAuthTokenInfo&gt;&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;Array&lt; [OAuthTokenInfo](#oauthtokeninfo8)&gt;&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1344,22 +1347,22 @@ Obtains information about all OAuth access tokens of an app account visible to t ...@@ -1344,22 +1347,22 @@ Obtains information about all OAuth access tokens of an app account visible to t
getAllOAuthTokens(name: string, owner: string): Promise&lt;Array&lt;OAuthTokenInfo&gt;&gt; getAllOAuthTokens(name: string, owner: string): Promise&lt;Array&lt;OAuthTokenInfo&gt;&gt;
Obtains information about all OAuth access tokens of an app account visible to the specified app. This method uses a promise to return the result. Obtains all OAuth tokens visible to the caller for an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------- | | ----- | ------ | ---- | ----------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ---------------------------------------- | --------------------- | | ---------------------------------------- | --------------------- |
| Promise&lt;Array&lt;OAuthTokenInfo&gt;&gt; | Promise used to return the result. | | Promise&lt;Array&lt; [OAuthTokenInfo](#oauthtokeninfo8)&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1376,17 +1379,17 @@ Obtains information about all OAuth access tokens of an app account visible to t ...@@ -1376,17 +1379,17 @@ Obtains information about all OAuth access tokens of an app account visible to t
getOAuthList(name: string, authType: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void getOAuthList(name: string, authType: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains the authorization list of OAuth access tokens of an app account. This method uses an asynchronous callback to return the result. Obtains a list of authorized OAuth tokens of an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------- | | -------- | ---------------------------------------- | ---- | ----------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | authType | string | Yes | Authorization type.|
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1402,22 +1405,22 @@ Obtains the authorization list of OAuth access tokens of an app account. This me ...@@ -1402,22 +1405,22 @@ Obtains the authorization list of OAuth access tokens of an app account. This me
getOAuthList(name: string, authType: string): Promise&lt;Array&lt;string&gt;&gt; getOAuthList(name: string, authType: string): Promise&lt;Array&lt;string&gt;&gt;
Obtains the authorization list of OAuth access tokens of an app account. This method uses a promise to return the result. Obtains a list of authorized OAuth tokens of an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------- | | -------- | ------ | ---- | ----------------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Bundle name of the app. | | authType | string | Yes | Authorization type.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ---------------------------------- | --------------------- | | ---------------------------------- | --------------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result. | | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1434,20 +1437,21 @@ Obtains the authorization list of OAuth access tokens of an app account. This me ...@@ -1434,20 +1437,21 @@ Obtains the authorization list of OAuth access tokens of an app account. This me
getAuthenticatorCallback(sessionId: string, callback: AsyncCallback&lt;AuthenticatorCallback&gt;): void getAuthenticatorCallback(sessionId: string, callback: AsyncCallback&lt;AuthenticatorCallback&gt;): void
Obtains the authenticator callback for a session. This method uses an asynchronous callback to return the result. Obtains the authenticator callback for an authentication session. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- | | --------- | ---------------------------------------- | ---- | -------- |
| sessionId | string | Yes | ID of the session to authenticate. | | sessionId | string | Yes | ID of the authentication session.|
| callback | AsyncCallback&lt;AuthenticatorCallback&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;[AuthenticatorCallback](#authenticatorcallback8)&gt; | Yes | Callback invoked to return the result.|
**Example** **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility';
const appAccountManager = account_appAccount.createAppAccountManager(); const appAccountManager = account_appAccount.createAppAccountManager();
featureAbility.getWant((err, want) => { featureAbility.getWant((err, want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
...@@ -1469,21 +1473,21 @@ Obtains the authenticator callback for a session. This method uses an asynchrono ...@@ -1469,21 +1473,21 @@ Obtains the authenticator callback for a session. This method uses an asynchrono
getAuthenticatorCallback(sessionId: string): Promise&lt;AuthenticatorCallback&gt; getAuthenticatorCallback(sessionId: string): Promise&lt;AuthenticatorCallback&gt;
Obtains the authenticator callback for a session. This method uses a promise to return the result. Obtains the authenticator callback for an authentication session. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | -------- | | --------- | ------ | ---- | -------- |
| sessionId | string | Yes | ID of the session to authenticate. | | sessionId | string | Yes | ID of the authentication session.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| ------------------------------------ | --------------------- | | ------------------------------------ | --------------------- |
| Promise&lt;AuthenticatorCallback&gt; | Promise used to return the result. | | Promise&lt;[AuthenticatorCallback](#authenticatorcallback8)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1509,16 +1513,16 @@ Obtains the authenticator callback for a session. This method uses a promise to ...@@ -1509,16 +1513,16 @@ Obtains the authenticator callback for a session. This method uses a promise to
getAuthenticatorInfo(owner: string, callback: AsyncCallback&lt;AuthenticatorInfo&gt;): void getAuthenticatorInfo(owner: string, callback: AsyncCallback&lt;AuthenticatorInfo&gt;): void
Obtains authenticator information of an app account. This method uses an asynchronous callback to return the result. Obtains authenticator information of an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------------- | ---- | ----------- | | -------- | -------------------------------------- | ---- | ----------- |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| callback | AsyncCallback&lt;AuthenticatorInfo&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;[AuthenticatorInfo](#authenticatorinfo8)&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1534,21 +1538,21 @@ Obtains authenticator information of an app account. This method uses an asynchr ...@@ -1534,21 +1538,21 @@ Obtains authenticator information of an app account. This method uses an asynchr
getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt; getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
Obtains authenticator information of an app account. This method uses a promise to return the result. Obtains authenticator information of an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------- | | ----- | ------ | ---- | ----------- |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
**Parameters** **Parameters**
| Type | Description | | Type | Description |
| -------------------------------- | --------------------- | | -------------------------------- | --------------------- |
| Promise&lt;AuthenticatorInfo&gt; | Promise used to return the result. | | Promise&lt;[AuthenticatorInfo](#authenticatorinfo8)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -1561,27 +1565,397 @@ Obtains authenticator information of an app account. This method uses a promise ...@@ -1561,27 +1565,397 @@ Obtains authenticator information of an app account. This method uses a promise
}); });
``` ```
### checkAppAccess<sup>9+</sup>
checkAppAccess(name: string, bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether an app account is authorized to access an app. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------- | ----- | ---------------- |
| name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app to check. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. |
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo", (err, data) => {
console.log('checkAppAccess: ' + JSON.stringify(data));
console.log("checkAppAccess err: " + JSON.stringify(err));
});
```
### checkAppAccess<sup>9+</sup>
checkAppAccess(name: string, bundleName: string): Promise&lt;boolean&gt;
Checks whether an app account is authorized to access an app. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------ | ----- | ---------------- |
| name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app to check. |
**Parameters**
| Type | Description |
| ---------------------- | --------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo").then((data) => {
console.log('checkAppAccess: ' + JSON.stringify(data));
}).catch((err) => {
console.log("checkAppAccess err: " + JSON.stringify(err));
});
```
### deleteAccountCredential<sup>9+</sup>
deleteAccountCredential(name: string, credentialType: string, callback: AsyncCallback&lt;void&gt;): void
Deletes the credential of an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ----- | -------------- |
| name | string | Yes | Name of the target app account.|
| credentialType | string | Yes | Type of the credential to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteAccountCredential("zhangsan", "pin", (err, data) => {
console.log('deleteAccountCredential: ' + JSON.stringify(data));
console.log("deleteAccountCredential err: " + JSON.stringify(err));
});
```
### deleteAccountCredential<sup>9+</sup>
deleteAccountCredential(name: string, credentialType: string): Promise&lt;void&gt;
Deletes the credential of an app account. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------ | ----- | --------------- |
| name | string | Yes | Name of the target app account.|
| credentialType | string | Yes | Type of the credential to delete. |
**Parameters**
| Type | Description |
| ------------------- | -------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteAccountCredential("zhangsan", "pin").then((data) => {
console.log('deleteAccountCredential: ' + JSON.stringify(data));
}).catch((err) => {
console.log("deleteAccountCredential err: " + JSON.stringify(err));
});
```
### checkAccountLabels<sup>9+</sup>
checkAccountLabels(name: string, owner: string, labels: Array&lt;string&gt;, callback: AsyncCallback&lt;boolean&gt;): void;
Checks whether an app account has specific labels. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ----- | --------------- |
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| labels | Array&lt;string&gt; | Yes | Labels to check. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", (err, data) => {
console.log('checkAccountLabels: ' + JSON.stringify(data));
console.log("checkAccountLabels err: " + JSON.stringify(err));
});
```
### checkAccountLabels<sup>9+</sup>
checkAccountLabels(name: string, owner: string, labels: Array&lt;string&gt;): Promise&lt;void&gt;
Checks whether an app account has specific labels. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ----- | --------------- |
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| labels | Array&lt;string&gt; | Yes | Labels to check. |
**Parameters**
| Type | Description |
| ------------------- | -------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo").then((data) => {
console.log('checkAccountLabels: ' + JSON.stringify(data));
}).catch((err) => {
console.log("checkAccountLabels err: " + JSON.stringify(err));
});
```
### selectAccountsByOptions<sup>9+</sup>
selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback&lt;Array&lt;AppAccountInfo&gt;&gt;);
Selects the accounts accessible to the requester based on the options. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ----------------------------------- | ----- | --------------- |
| options | SelectAccountsOptions | Yes | Options for selecting accounts. |
| callback | AsyncCallback&lt;[AppAccountInfo](#appaccountinfo)&gt; | Yes | Callback invoked to return the result. |
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
var options = {
allowedOwners: ["com.example.ohos.accountjsdemo"]
};
appAccountManager.selectAccountsByOptions(options, (err, data) => {
console.log('selectAccountsByOptions: ' + JSON.stringify(data));
console.log("selectAccountsByOptions err: " + JSON.stringify(err));
});
```
### selectAccountsByOptions<sup>9+</sup>
selectAccountsByOptions(options: SelectAccountsOptions): Promise&lt;void&gt;
Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ----- | --------------- |
| options | [SelectAccountsOptions](#selectaccountsoptions9) | Yes | Options for selecting accounts. |
**Parameters**
| Type | Description |
| ------------------- | -------------------------------- |
| Promise&lt;[AppAccountInfo](#appaccountinfo)&gt; | Promise used to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
var options = {
allowedOwners: ["com.example.ohos.accountjsdemo"]
};
appAccountManager.selectAccountsByOptions(options).then((data) => {
console.log('selectAccountsByOptions: ' + JSON.stringify(data));
}).catch((err) => {
console.log("selectAccountsByOptions err: " + JSON.stringify(err));
});
```
### verifyCredential<sup>9+</sup>
verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void;
Verifies the user credential. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------- | ----- | ----------------------- |
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", {
onResult: (resultCode, result) => {
console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode));
console.log("verifyCredential onResult, result:" + JSON.stringify(result));
},
onRequestRedirected: (request) => {
console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request));
}
});
```
### verifyCredential<sup>9+</sup>
verifyCredential(name: string, owner: string, options, callback: AuthenticatorCallback): void;
Verifies the user credential. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | ----- | ----------------------- |
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for verifying the user credential. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
var options = {
credentialType: "pin",
credential: "123456"
};
appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", options, {
onResult: (resultCode, result) => {
console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode));
console.log("verifyCredential onResult, result:" + JSON.stringify(result));
},
onRequestRedirected: (request) => {
console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request));
}
});
```
### setAuthenticatorProperties<sup>9+</sup>
setAuthenticatorProperties(owner: string, callback: AuthenticatorCallback): void;
Sets authenticator properties. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------- | ----- | ----------------------- |
| owner | string | Yes | Owner of the authenticator. |
| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", {
onResult: (resultCode, result) => {
console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode));
console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result));
},
onRequestRedirected: (request) => {
console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request));
}
});
```
### setAuthenticatorProperties<sup>9+</sup>
setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthenticatorCallback): void;
Sets authenticator properties. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------- | ----- | ----------------------- |
| owner | string | Yes | Owner of the authenticator. |
| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.|
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
var options = {
properties: {"prop1": "value1"}
};
appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", options, {
onResult: (resultCode, result) => {
console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode));
console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result));
},
onRequestRedirected: (request) => {
console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request));
}
});
```
## AppAccountInfo ## AppAccountInfo
Defines app account information. Defines app account information.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------- | | ----- | ------ | ---- | ----------- |
| owner | string | Yes | Bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.|
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
## OAuthTokenInfo<sup>8+</sup> ## OAuthTokenInfo<sup>8+</sup>
Defines OAuth access token information. Defines OAuth token information.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ---- | -------- | | -------- | ------ | ---- | -------- |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type.|
| token | string | Yes | Value of the access token. | | token | string | Yes | Value of the token. |
## AuthenticatorInfo<sup>8+</sup> ## AuthenticatorInfo<sup>8+</sup>
...@@ -1589,11 +1963,47 @@ Defines OAuth authenticator information. ...@@ -1589,11 +1963,47 @@ Defines OAuth authenticator information.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---------- | | ------- | ------ | ---- | ---------- |
| owner | string | Yes | Bundle name of the authenticator owner. | | owner | string | Yes | Owner of the authenticator. The value is the bundle name of the app.|
| iconId | string | Yes | ID of the authenticator icon. | | iconId | string | Yes | ID of the authenticator icon. |
| labelId | string | Yes | ID of the authenticator label. | | labelId | string | Yes | ID of the authenticator label. |
## SelectAccountsOptions<sup>9+</sup>
Represents the options for selecting accounts.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description |
| --------------- | --------------------------- | ----- | ------------------- |
| allowedAccounts | Array&lt;[AppAccountInfo](#appAccountinfo)&gt; | No | Allowed accounts. |
| allowedOwners | Array&lt;string&gt; | No | Allowed account owners.|
| requiredLabels | Array&lt;string&gt; | No | Labels required for the authenticator. |
## VerifyCredentialOptions<sup>9+</sup>
Represents the options for verifying the user credential.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description |
| -------------- | ---------------------- | ----- | -------------- |
| credentialType | string | No | Type of the credential to verify. |
| credential | string | No | Credential value. |
| parameters | {[key:string]: Object} | No | Customized parameters.|
## SetPropertiesOptions<sup>9+</sup>
Represents the options for setting authenticator properties.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Mandatory | Description |
| ---------- | ---------------------- | ----- | -------------- |
| properties | {[key:string]: Object} | No | Authenticator properties to set. |
| parameters | {[key:string]: Object} | No | Customized parameters.|
## Constants<sup>8+</sup> ## Constants<sup>8+</sup>
...@@ -1601,19 +2011,21 @@ Enumerates the constants. ...@@ -1601,19 +2011,21 @@ Enumerates the constants.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
| Name | Default Value | Description | | Name | Default Value | Description |
| ----------------------------- | ---------------------- | ------------- | | ----------------------------- | ---------------------- | ------------- |
| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation for implicitly adding an account. | | ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. |
| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | | ACTION_AUTHENTICATE | "authenticate" | Authentication operation. |
| KEY_NAME | "name" | App account name. | | KEY_NAME | "name" | App account name. |
| KEY_OWNER | "owner" | App account owner. | | KEY_OWNER | "owner" | Owner of an app account.|
| KEY_TOKEN | "token" | OAuth access token. | | KEY_TOKEN | "token" | Token. |
| KEY_ACTION | "action" | Action. | | KEY_ACTION | "action" | Operation. |
| KEY_AUTH_TYPE | "authType" | Authentication type. | | KEY_AUTH_TYPE | "authType" | Authentication type. |
| KEY_SESSION_ID | "sessionId" | Session ID. | | KEY_SESSION_ID | "sessionId" | Session ID. |
| KEY_CALLER_PID | "callerPid" | Caller process ID (PID). | | KEY_CALLER_PID | "callerPid" | PID of the caller. |
| KEY_CALLER_UID | "callerUid" | Caller user ID (UID). | | KEY_CALLER_UID | "callerUid" | UID of the caller. |
| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Caller bundle name. | | KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. |
| KEY_REQUIRED_LABELS | "requiredLabels" | Required labels. |
| KEY_BOOLEAN_RESULT | "booleanResult" | Return value of the Boolean type. |
## ResultCode<sup>8+</sup> ## ResultCode<sup>8+</sup>
...@@ -1621,45 +2033,45 @@ Enumerates the result codes. ...@@ -1621,45 +2033,45 @@ Enumerates the result codes.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
| Name | Default Value | Description | | Name | Default Value | Description |
| ----------------------------------- | ----- | ------------ | | ----------------------------------- | ----- | ------------ |
| SUCCESS | 0 | The operation is successful. | | SUCCESS | 0 | The operation is successful. |
| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | | ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. |
| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | | ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. |
| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | | ERROR_INVALID_PASSWORD | 10003 | The password is invalid. |
| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | | ERROR_INVALID_REQUEST | 10004 | The request is invalid. |
| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | | ERROR_INVALID_RESPONSE | 10005 | The response is invalid. |
| ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. | | ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. |
| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. | | ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. |
| ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. | | ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. |
| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. | | ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. |
| ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. | | ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. |
| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | | ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. |
| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | | ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. |
| ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | | ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. |
| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth access token does not exist. | | ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth token does not exist.|
| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth access tokens reaches the limit. | | ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth tokens reaches the limit. |
| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | | ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. |
| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | | ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. |
| ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | | ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. |
## AuthenticatorCallback<sup>8+</sup> ## AuthenticatorCallback<sup>8+</sup>
Provides methods for managing the OAuth authenticator callback. Provides OAuth authenticator callbacks.
### onResult<sup>8+</sup> ### onResult<sup>8+</sup>
onResult: (code: number, result: {[key: string]: any}) =&gt; void onResult: (code: number, result: {[key: string]: any}) =&gt; void
Called back to send the authentication result. Returns the result of an authentication request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | -------------------- | ---- | ------ | | ------ | -------------------- | ---- | ------ |
| code | number | Yes | Authentication result code. | | code | number | Yes | Authentication result code.|
| result | {[key: string]: any} | Yes | Authentication result. | | result | {[key: string]: any} | Yes | Authentication result. |
**Example** **Example**
...@@ -1681,14 +2093,14 @@ Called back to send the authentication result. ...@@ -1681,14 +2093,14 @@ Called back to send the authentication result.
onRequestRedirected: (request: Want) =&gt; void onRequestRedirected: (request: Want) =&gt; void
Called back to redirect an authentication request. Redirects a request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---- | ---- | ---------- | | ------- | ---- | ---- | ---------- |
| request | Want | Yes | Request to be redirected. | | request | Want | Yes | Request to be redirected.|
**Example** **Example**
...@@ -1710,42 +2122,128 @@ Called back to redirect an authentication request. ...@@ -1710,42 +2122,128 @@ Called back to redirect an authentication request.
} }
``` ```
### onRequestContinued<sup>9+</sup>
onRequestContinued: () =&gt; void
Continues to process the request.
**System capability**: SystemCapability.Account.AppAccount
**Example**
```js
const appAccountManager = account_appAccount.createAppAccountManager();
var sessionId = "1234";
appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
callback.OnRequestContinued();
}).catch((err) => {
console.log("getAuthenticatorCallback err: " + JSON.stringify(err));
});
```
## Authenticator<sup>8+</sup> ## Authenticator<sup>8+</sup>
Defines the OAuth authenticator base class. Provides APIs to operate the authenticator.
### addAccountImplicitly<sup>8+</sup> ### addAccountImplicitly<sup>8+</sup>
addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
Implicitly adds an app account based on the specified authentication type and options. This method uses an asynchronous callback to return the result. Implicitly adds an app account based on the specified authentication type and options. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| callerBundleName | string | Yes | Bundle name of the authentication requester. | | callerBundleName | string | Yes | Bundle name of the authentication requester. |
| options | {[key: string]: any} | Yes | Options for the authentication. | | options | {[key: string]: any} | Yes | Options for the authentication. |
| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result. | | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.|
### authenticate<sup>8+</sup> ### authenticate<sup>8+</sup>
authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
Authenticates an app account to obtain the OAuth access token. This method uses an asynchronous callback to return the result. Authenticates an app account to obtain the OAuth access token. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. |
| callerBundleName | string | Yes | Bundle name of the authentication requester. |
| options | {[key: string]: any} | Yes | Options for the authentication. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.|
### verifyCredential<sup>9+</sup>
verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void;
Verifies the app account credential. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. |
| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Optional for credential verification. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.|
### setProperties<sup>9+</sup>
setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback): void;
Sets authenticator properties. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- |
| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.|
### checkAccountLabels<sup>9+</sup>
checkAccountLabels(name: string, labels: Array&lt;string&gt;, callback: AuthenticatorCallback): void;
Checks the account labels. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | App account name. | | name | string | Yes | Name of the target app account. |
| authType | string | Yes | Authentication type. | | labels | Array&lt;string&gt; | Yes | Labels to check. |
| callerBundleName | string | Yes | Bundle name of the authentication requester. | | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the check result.|
| options | {[key: string]: any} | Yes | Options for the authentication. |
| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result. | ### isAccountRemovable<sup>9+</sup>
isAccountRemovable(name: string, callback: AuthenticatorCallback): void;
Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.|
### getRemoteObject<sup>9+</sup>
getRemoteObject(): rpc.RemoteObject;
Obtains the remote object of an authenticator. This API cannot be overloaded.
**System capability**: SystemCapability.Account.AppAccount
**Example** **Example**
...@@ -1764,11 +2262,36 @@ Authenticates an app account to obtain the OAuth access token. This method uses ...@@ -1764,11 +2262,36 @@ Authenticates an app account to obtain the OAuth access token. This method uses
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
} }
verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback) {
callback.onRequestRedirected({
bundleName: "com.example.ohos.accountjsdemo",
abilityName: "com.example.ohos.accountjsdemo.VerifyAbility",
parameters: {
name: name
}
});
} }
setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback) {
callback.onResult(account_appAccount.ResultCode.SUCCESS, {});
}
checkAccountLabels(name: string, labels: Array<string>, callback: AuthenticatorCallback) {
var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
isAccountRemovable(name, callback) {
var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
}
var authenticator = null;
export default { export default {
onConnect(want) { onConnect(want) {
return new MyAuthenticator(); authenticator = new MyAuthenticator();
return authenticator.getRemoteObject();
} }
} }
``` ```
# Bluetooth # Bluetooth
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. Provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
## Modules to Import ## Modules to Import
...@@ -201,7 +201,7 @@ Obtains the connection state of a profile. ...@@ -201,7 +201,7 @@ Obtains the connection state of a profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- | | --------- | --------- | ---- | ------------------------------------- |
| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| | ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.|
**Return value** **Return value**
...@@ -212,7 +212,7 @@ Obtains the connection state of a profile. ...@@ -212,7 +212,7 @@ Obtains the connection state of a profile.
**Example** **Example**
```js ```js
let result = bluetooth.getProfileConnState(PROFILE_A2DP_SOURCE); let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
``` ```
...@@ -355,7 +355,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de ...@@ -355,7 +355,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de
```js ```js
// The device can be discovered and connected only when the discoverable and connectable mode is used. // The device can be discovered and connected only when the discoverable and connectable mode is used.
let result = bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
``` ```
...@@ -720,7 +720,7 @@ bluetooth.off('stateChange', onReceiveEvent); ...@@ -720,7 +720,7 @@ bluetooth.off('stateChange', onReceiveEvent);
``` ```
## bluetooth.sppListen<sup>8+</sup><a name="sppListen<"></a> ## bluetooth.sppListen<sup>8+</sup><a name="sppListen"></a>
sppListen(name: string, option: SppOption, callback: AsyncCallback&lt;number&gt;): void sppListen(name: string, option: SppOption, callback: AsyncCallback&lt;number&gt;): void
...@@ -773,6 +773,14 @@ Listens for a connection to be made to this socket from the client and accepts i ...@@ -773,6 +773,14 @@ Listens for a connection to be made to this socket from the client and accepts i
**Example** **Example**
```js ```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
let clientNumber = -1; let clientNumber = -1;
function acceptClientSocket(code, number) { function acceptClientSocket(code, number) {
console.log('bluetooth error code: ' + code.code); console.log('bluetooth error code: ' + code.code);
...@@ -807,6 +815,7 @@ Initiates an SPP connection to a remote device from the client. ...@@ -807,6 +815,7 @@ Initiates an SPP connection to a remote device from the client.
**Example** **Example**
```js ```js
let clientNumber = -1; let clientNumber = -1;
function clientSocket(code, number) { function clientSocket(code, number) {
if (code.code != 0) { if (code.code != 0) {
...@@ -838,6 +847,14 @@ Closes the listening socket of the server. ...@@ -838,6 +847,14 @@ Closes the listening socket of the server.
**Example** **Example**
```js ```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
bluetooth.sppCloseServerSocket(serverNumber); bluetooth.sppCloseServerSocket(serverNumber);
``` ```
...@@ -860,6 +877,15 @@ Closes the client socket. ...@@ -860,6 +877,15 @@ Closes the client socket.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.sppCloseClientSocket(clientNumber); bluetooth.sppCloseClientSocket(clientNumber);
``` ```
...@@ -888,6 +914,15 @@ Writes data to the remote device through the socket. ...@@ -888,6 +914,15 @@ Writes data to the remote device through the socket.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
let arrayBuffer = new ArrayBuffer(8); let arrayBuffer = new ArrayBuffer(8);
let data = new Uint8Array(arrayBuffer); let data = new Uint8Array(arrayBuffer);
data[0] = 123; data[0] = 123;
...@@ -923,6 +958,15 @@ No value is returned. ...@@ -923,6 +958,15 @@ No value is returned.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
function dataRead(dataBuffer) { function dataRead(dataBuffer) {
let data = new Uint8Array(dataBuffer); let data = new Uint8Array(dataBuffer);
console.log('bluetooth data is: ' + data[0]); console.log('bluetooth data is: ' + data[0]);
...@@ -954,6 +998,15 @@ No value is returned. ...@@ -954,6 +998,15 @@ No value is returned.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.off('sppRead', clientNumber); bluetooth.off('sppRead', clientNumber);
``` ```
...@@ -981,14 +1034,14 @@ Obtains a profile object. ...@@ -981,14 +1034,14 @@ Obtains a profile object.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
``` ```
## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a> ## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a>
getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile
Obtains the profile object instance based on **ProfileId**. API version 9 is added with **HidHostProfile**. Obtains a profile instance. **HidHostProfile** is added in API version 9.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -996,7 +1049,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add ...@@ -996,7 +1049,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- | | --------- | --------- | ---- | ------------------------------------- |
| profileId | [ProfileId](#ProfileId) | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| | profileId | [ProfileId](#ProfileId) | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.|
**Return value** **Return value**
...@@ -1007,7 +1060,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add ...@@ -1007,7 +1060,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add
**Example** **Example**
```js ```js
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST); let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
``` ```
...@@ -1239,7 +1292,7 @@ No value is returned. ...@@ -1239,7 +1292,7 @@ No value is returned.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let retArray = a2dpSrc.getConnectionDevices(); let retArray = a2dpSrc.getConnectionDevices();
``` ```
...@@ -1257,7 +1310,7 @@ Obtains the connection state of the profile. ...@@ -1257,7 +1310,7 @@ Obtains the connection state of the profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1268,7 +1321,7 @@ Obtains the connection state of the profile. ...@@ -1268,7 +1321,7 @@ Obtains the connection state of the profile.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1277,7 +1330,7 @@ let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); ...@@ -1277,7 +1330,7 @@ let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');
Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method. Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a> ### connect<sup>8+</sup><a name="a2dp-connect"></a>
connect(device: string): boolean connect(device: string): boolean
...@@ -1302,12 +1355,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. ...@@ -1302,12 +1355,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX');
``` ```
### disconnect<sup>8+</sup><a name="disconnect"></a> ### disconnect<sup>8+</sup><a name="a2dp-disconnect"></a>
disconnect(device: string): boolean disconnect(device: string): boolean
...@@ -1332,7 +1385,7 @@ Disconnects an A2DP connection. ...@@ -1332,7 +1385,7 @@ Disconnects an A2DP connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1362,7 +1415,7 @@ No value is returned. ...@@ -1362,7 +1415,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data)); console.info('a2dp state = '+ JSON.stringify(data));
} }
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1392,7 +1445,7 @@ No value is returned. ...@@ -1392,7 +1445,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data)); console.info('a2dp state = '+ JSON.stringify(data));
} }
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.on('connectionStateChange', onReceiveEvent);
a2dpSrc.off('connectionStateChange', onReceiveEvent); a2dpSrc.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1410,7 +1463,7 @@ Obtains the playing state of a device. ...@@ -1410,7 +1463,7 @@ Obtains the playing state of a device.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1421,7 +1474,7 @@ Obtains the playing state of a device. ...@@ -1421,7 +1474,7 @@ Obtains the playing state of a device.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1431,7 +1484,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); ...@@ -1431,7 +1484,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method. Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a> ### connect<sup>8+</sup><a name="hfp-connect"></a>
connect(device: string): boolean connect(device: string): boolean
...@@ -1445,7 +1498,7 @@ Sets up a Hands-free Profile (HFP) connection of a device. ...@@ -1445,7 +1498,7 @@ Sets up a Hands-free Profile (HFP) connection of a device.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1456,12 +1509,12 @@ Sets up a Hands-free Profile (HFP) connection of a device. ...@@ -1456,12 +1509,12 @@ Sets up a Hands-free Profile (HFP) connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX');
``` ```
### disconnect<sup>8+</sup><a name="disconnect"></a> ### disconnect<sup>8+</sup><a name="hfp-disconnect"></a>
disconnect(device: string): boolean disconnect(device: string): boolean
...@@ -1475,7 +1528,7 @@ Disconnects the HFP connection of a device. ...@@ -1475,7 +1528,7 @@ Disconnects the HFP connection of a device.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1486,7 +1539,7 @@ Disconnects the HFP connection of a device. ...@@ -1486,7 +1539,7 @@ Disconnects the HFP connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1516,7 +1569,7 @@ No value is returned. ...@@ -1516,7 +1569,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data)); console.info('hfp state = '+ JSON.stringify(data));
} }
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1546,7 +1599,7 @@ No value is returned. ...@@ -1546,7 +1599,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data)); console.info('hfp state = '+ JSON.stringify(data));
} }
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.on('connectionStateChange', onReceiveEvent);
hfpAg.off('connectionStateChange', onReceiveEvent); hfpAg.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1573,7 +1626,7 @@ Connects to the HidHost service of a device. ...@@ -1573,7 +1626,7 @@ Connects to the HidHost service of a device.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1584,7 +1637,7 @@ Connects to the HidHost service of a device. ...@@ -1584,7 +1637,7 @@ Connects to the HidHost service of a device.
**Example** **Example**
```js ```js
let hidHostProfile = bluetooth.getProfile(PROFILE_HID_HOST); let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1605,7 +1658,7 @@ Disconnects from the HidHost service of a device. ...@@ -1605,7 +1658,7 @@ Disconnects from the HidHost service of a device.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1616,7 +1669,7 @@ Disconnects from the HidHost service of a device. ...@@ -1616,7 +1669,7 @@ Disconnects from the HidHost service of a device.
**Example** **Example**
```js ```js
let hidHostProfile = bluetooth.getProfile(PROFILE_HID_HOST); let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1646,7 +1699,7 @@ No value is returned. ...@@ -1646,7 +1699,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data)); console.info('hidHost state = '+ JSON.stringify(data));
} }
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST); let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
hidHost.on('connectionStateChange', onReceiveEvent); hidHost.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1676,7 +1729,7 @@ No value is returned. ...@@ -1676,7 +1729,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data)); console.info('hidHost state = '+ JSON.stringify(data));
} }
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST); let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
hidHost.on('connectionStateChange', onReceiveEvent); hidHost.on('connectionStateChange', onReceiveEvent);
hidHost.off('connectionStateChange', onReceiveEvent); hidHost.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1819,7 +1872,7 @@ cccV[0] = 1; ...@@ -1819,7 +1872,7 @@ cccV[0] = 1;
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptorsN}; characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
characteristics[0] = characteristic; characteristics[0] = characteristic;
// Create a gattService instance. // Create a gattService instance.
...@@ -1911,8 +1964,11 @@ Notifies the connected client device when a characteristic value changes. ...@@ -1911,8 +1964,11 @@ Notifies the connected client device when a characteristic value changes.
**Example** **Example**
```js ```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: notifyCcc.characteristicValue, confirm: false}; characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false};
let server = bluetooth.BLE.createGattServer(); let server = bluetooth.BLE.createGattServer();
server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic);
``` ```
...@@ -2138,7 +2194,7 @@ Subscribes to the descriptor read request events. ...@@ -2138,7 +2194,7 @@ Subscribes to the descriptor read request events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------- | | -------- | ---------------------------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.|
| callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request from the GATT client. | | callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request event from the GATT client. |
**Return value** **Return value**
...@@ -2279,7 +2335,6 @@ let gattServer = bluetooth.BLE.createGattServer(); ...@@ -2279,7 +2335,6 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite"); gattServer.off("descriptorWrite");
``` ```
### on('connectStateChange') ### on('connectStateChange')
on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void
...@@ -2488,7 +2543,7 @@ Obtains all services of the remote BLE device. This API uses a promise to return ...@@ -2488,7 +2543,7 @@ Obtains all services of the remote BLE device. This API uses a promise to return
// Promise // Promise
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect(); device.connect();
let services = device.getServices(); var services = device.getServices();
console.log("bluetooth services size is ", services.length); console.log("bluetooth services size is ", services.length);
for (let i = 0; i < services.length; i++) { for (let i = 0; i < services.length; i++) {
...@@ -2826,8 +2881,11 @@ Sets the function of notifying the GATT client when the characteristic value of ...@@ -2826,8 +2881,11 @@ Sets the function of notifying the GATT client when the characteristic value of
**Example** **Example**
```js ```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.setNotifyCharacteristicChanged(notifyCcc, false); device.setNotifyCharacteristicChanged(characteristic, false);
``` ```
...@@ -3296,11 +3354,19 @@ Defines the scan filter parameters. ...@@ -3296,11 +3354,19 @@ Defines the scan filter parameters.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Type | Readable | Writable | Description | | Name | Type | Readable| Writable| Description |
| ----------- | ------ | ---- | ---- | ---------------------------------------- | | ---------------------------------------- | ----------- | ---- | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. | | deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. |
| name | string | Yes | Yes | Name of the BLE device to filter. | | name | string | Yes | Yes | Name of the BLE device to filter. |
| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| | serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.|
| serviceUuidMask<sup>9+</sup> | string | Yes | Yes | Service UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.|
| serviceSolicitationUuid<sup>9+</sup> | string | Yes | Yes | Service solicitation UUID of the device to filter, for example, **00001888-0000-1000-8000-00805F9B34FB**.|
| serviceSolicitationUuidMask<sup>9+</sup> | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.|
| serviceData<sup>9+</sup> | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.|
| serviceDataMask<sup>9+</sup> | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.|
| manufacturerId<sup>9+</sup> | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. |
| manufactureData<sup>9+</sup> | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.|
| manufactureDataMask<sup>9+</sup> | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.|
## ScanOptions ## ScanOptions
......
# Relational Database # Relational Database
The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
This module provides the following RDB-related functions:
- [RdbPredicates](#rdbpredicates): predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store.
- [RdbStore](#rdbstore): provides APIs for managing an RDB store.
> **NOTE**<br/> > **NOTE**<br/>
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -11,71 +19,9 @@ import data_rdb from '@ohos.data.rdb'; ...@@ -11,71 +19,9 @@ import data_rdb from '@ohos.data.rdb';
## data_rdb.getRdbStore ## data_rdb.getRdbStore
getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback&lt;RdbStore&gt;): void
Obtains a relational database (RDB) store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.|
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.|
**Example**
```js
const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
```
## data_rdb.getRdbStore
getRdbStore(config: StoreConfig, version: number): Promise&lt;RdbStore&gt;
Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[RdbStore](#rdbstore)&gt; | Promise used to return the RDB store obtained.|
**Example**
```js
const STORE_CONFIG = { name: "RdbTest.db" }
let promise = data_rdb.getRdbStore(STORE_CONFIG, 1);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
```
## data_rdb.getRdbStore<sup>8+</sup>
getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback&lt;RdbStore&gt;): void getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback&lt;RdbStore&gt;): void
Obtains a RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -83,7 +29,7 @@ Obtains a RDB store. This API uses an asynchronous callback to return the result ...@@ -83,7 +29,7 @@ Obtains a RDB store. This API uses an asynchronous callback to return the result
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context<sup>8+</sup> | Context | Yes| Context of the app or functionality.<br>For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).<br>For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.| | callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.|
...@@ -101,7 +47,7 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { ...@@ -101,7 +47,7 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
}) })
``` ```
## data_rdb.getRdbStore<sup>8+</sup> ## data_rdb.getRdbStore
getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt; getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt;
...@@ -113,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -113,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context<sup>8+</sup> | Context | Yes| Context of the app or functionality.<br>For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).<br>For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
...@@ -137,68 +83,16 @@ promise.then(async (rdbStore) => { ...@@ -137,68 +83,16 @@ promise.then(async (rdbStore) => {
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
deleteRdbStore(name: string, callback: AsyncCallback&lt;void&gt;): void
Deletes an RDB store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the RDB store to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example**
```js
data_rdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
```
## data_rdb.deleteRdbStore
deleteRdbStore(name: string): Promise&lt;void&gt;
Deletes an RDB store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the RDB store to delete.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
let promise = data_rdb.deleteRdbStore("RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
```
## data_rdb.deleteRdbStore<sup>8+</sup>
deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Deletes an RDB store. This API uses a callback to return the result. Deletes an RDB store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context<sup>8+</sup> | Context | Yes| Context of the app or functionality.<br>For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).<br>For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
...@@ -213,7 +107,7 @@ data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { ...@@ -213,7 +107,7 @@ data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) {
}) })
``` ```
## data_rdb.deleteRdbStore<sup>8+</sup> ## data_rdb.deleteRdbStore
deleteRdbStore(context: Context, name: string): Promise&lt;void&gt; deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
...@@ -224,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -224,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context<sup>8+</sup> | Context | Yes| Context of the app or functionality.<br>For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).<br>For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
**Return value** **Return value**
...@@ -234,7 +128,7 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -234,7 +128,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let promise = data_rdb.deleteRdbStore("RdbTest.db") let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -1090,7 +984,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { ...@@ -1090,7 +984,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) {
console.info("Failed to insert data, err: " + err) console.info("Failed to insert data, err: " + err)
return return
} }
console.log("Insert first done: " + ret) console.log("Inserted first row: " + ret)
}) })
``` ```
...@@ -1215,7 +1109,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje ...@@ -1215,7 +1109,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.|
**Example** **Example**
...@@ -1239,7 +1133,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { ...@@ -1239,7 +1133,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
``` ```
### update<sup>9+</sup> ### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt; update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt;
Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
...@@ -1300,7 +1194,7 @@ rdbStore.delete(predicates, function (err, rows) { ...@@ -1300,7 +1194,7 @@ rdbStore.delete(predicates, function (err, rows) {
console.info("Failed to delete data, err: " + err) console.info("Failed to delete data, err: " + err)
return return
} }
console.log("Delete rows: " + rows) console.log("Deleted rows: " + rows)
}) })
``` ```
...@@ -1329,7 +1223,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -1329,7 +1223,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
let promise = rdbStore.delete(predicates) let promise = rdbStore.delete(predicates)
promise.then((rows) => { promise.then((rows) => {
console.log("Delete rows: " + rows) console.log("Deleted rows: " + rows)
}).catch((err) => { }).catch((err) => {
console.info("Failed to delete data, err: " + err) console.info("Failed to delete data, err: " + err)
}) })
...@@ -1337,7 +1231,7 @@ promise.then((rows) => { ...@@ -1337,7 +1231,7 @@ promise.then((rows) => {
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
...@@ -1361,12 +1255,12 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { ...@@ -1361,12 +1255,12 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) {
console.info("Failed to delete data, err: " + err) console.info("Failed to delete data, err: " + err)
return return
} }
console.log("Delete rows: " + rows) console.log("Deleted rows: " + rows)
}) })
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(table: string, predicates: DataSharePredicates):Promise&lt;number&gt; delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
...@@ -1390,7 +1284,7 @@ let predicates = new dataSharePredicates.DataSharePredicates() ...@@ -1390,7 +1284,7 @@ let predicates = new dataSharePredicates.DataSharePredicates()
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
let promise = rdbStore.delete("EMPLOYEE", predicates) let promise = rdbStore.delete("EMPLOYEE", predicates)
promise.then((rows) => { promise.then((rows) => {
console.log("Delete rows: " + rows) console.log("Deleted rows: " + rows)
}).catch((err) => { }).catch((err) => {
console.info("Failed to delete data, err: " + err) console.info("Failed to delete data, err: " + err)
}) })
...@@ -1417,7 +1311,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -1417,7 +1311,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose") predicates.equalTo("NAME", "Rose")
rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) {
if (err) { if (err) {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
return return
} }
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
...@@ -1454,13 +1348,13 @@ Queries data in the database based on specified conditions. This API uses a prom ...@@ -1454,13 +1348,13 @@ Queries data in the database based on specified conditions. This API uses a prom
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
console.log("ResultSet column count: " + resultSet.columnCount) console.log("ResultSet column count: " + resultSet.columnCount)
}).catch((err) => { }).catch((err) => {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
}) })
``` ```
### query<sup>9+</sup> ### query<sup>9+</sup>
query(predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result.
...@@ -1480,7 +1374,7 @@ let predicates = new dataSharePredicates.DataSharePredicates() ...@@ -1480,7 +1374,7 @@ let predicates = new dataSharePredicates.DataSharePredicates()
predicates.equalTo("NAME", "Rose") predicates.equalTo("NAME", "Rose")
rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) {
if (err) { if (err) {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
return return
} }
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
...@@ -1490,7 +1384,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], ...@@ -1490,7 +1384,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
### query<sup>9+</sup> ### query<sup>9+</sup>
query(predicates: dataSharePredicates.DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the database based on specified conditions. This API uses a promise to return the result. Queries data in the database based on specified conditions. This API uses a promise to return the result.
...@@ -1517,7 +1411,7 @@ promise.then((resultSet) => { ...@@ -1517,7 +1411,7 @@ promise.then((resultSet) => {
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
console.log("ResultSet column count: " + resultSet.columnCount) console.log("ResultSet column count: " + resultSet.columnCount)
}).catch((err) => { }).catch((err) => {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
}) })
``` ```
...@@ -1540,7 +1434,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ...@@ -1540,7 +1434,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a
```js ```js
rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) {
if (err) { if (err) {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
return return
} }
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
...@@ -1575,7 +1469,7 @@ promise.then((resultSet) => { ...@@ -1575,7 +1469,7 @@ promise.then((resultSet) => {
console.log("ResultSet column names: " + resultSet.columnNames) console.log("ResultSet column names: " + resultSet.columnNames)
console.log("ResultSet column count: " + resultSet.columnCount) console.log("ResultSet column count: " + resultSet.columnCount)
}).catch((err) => { }).catch((err) => {
console.info("Query failed, err: " + err) console.info("Failed to query data, err: " + err)
}) })
``` ```
...@@ -1600,7 +1494,7 @@ Runs the SQL statement that contains the specified parameters but does not retur ...@@ -1600,7 +1494,7 @@ Runs the SQL statement that contains the specified parameters but does not retur
const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)"
rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) {
if (err) { if (err) {
console.info("ExecuteSql failed, err: " + err) console.info("Failed to execute SQL, err: " + err)
return return
} }
console.info('Create table done.') console.info('Create table done.')
...@@ -1634,7 +1528,7 @@ let promise = rdbStore.executeSql(SQL_CREATE_TABLE) ...@@ -1634,7 +1528,7 @@ let promise = rdbStore.executeSql(SQL_CREATE_TABLE)
promise.then(() => { promise.then(() => {
console.info('Create table done.') console.info('Create table done.')
}).catch((err) => { }).catch((err) => {
console.info("ExecuteSql failed, err: " + err) console.info("Failed to execute SQL, err: " + err)
}) })
``` ```
...@@ -1745,10 +1639,10 @@ Backs up the database with the specified name. This API uses an asynchronous cal ...@@ -1745,10 +1639,10 @@ Backs up the database with the specified name. This API uses an asynchronous cal
```js ```js
rdbStore.backup("dbBackup.db", function(err) { rdbStore.backup("dbBackup.db", function(err) {
if (err) { if (err) {
console.info('Backup failed, err: ' + err) console.info('Failed to back up data, err: ' + err)
return return
} }
console.info('Backup success.') console.info('Backup successful.')
}) })
``` ```
...@@ -1774,9 +1668,9 @@ Backs up the database with the specified name. This API uses a promise to return ...@@ -1774,9 +1668,9 @@ Backs up the database with the specified name. This API uses a promise to return
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(()=>{ promiseBackup.then(()=>{
console.info('Backup success.') console.info('Backup successful.')
}).catch((err)=>{ }).catch((err)=>{
console.info('Backup failed, err: ' + err) console.info('Failed to back up data, err: ' + err)
}) })
``` ```
...@@ -1798,10 +1692,10 @@ Restores a database from a specified database backup file. This API uses an asyn ...@@ -1798,10 +1692,10 @@ Restores a database from a specified database backup file. This API uses an asyn
```js ```js
rdbStore.restore("dbBackup.db", function(err) { rdbStore.restore("dbBackup.db", function(err) {
if (err) { if (err) {
console.info('Restore failed, err: ' + err) console.info('Failed to restore data, err: ' + err)
return return
} }
console.info('Restore success.') console.info('Restore successful.')
}) })
``` ```
...@@ -1827,9 +1721,9 @@ Restores a database from a specified database backup file. This API uses a promi ...@@ -1827,9 +1721,9 @@ Restores a database from a specified database backup file. This API uses a promi
```js ```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(()=>{ promiseRestore.then(()=>{
console.info('Restore success.') console.info('Restore successful.')
}).catch((err)=>{ }).catch((err)=>{
console.info('Restore failed, err: ' + err) console.info('Failed to restore data, err: ' + err)
}) })
``` ```
...@@ -1910,12 +1804,12 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1910,12 +1804,12 @@ Obtains the distributed table name for a remote device based on the local table
**Example** **Example**
```js ```js
rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) {
if (err) { if (err) {
console.info('Failed to obtain distributed table name, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
return return
} }
console.info('Obtained distributed table name successfully, tableName=.' + tableName) console.info('Obtained DistributedTableName successfully, tableName=.' + tableName)
}) })
``` ```
...@@ -1943,11 +1837,11 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1943,11 +1837,11 @@ Obtains the distributed table name for a remote device based on the local table
**Example** **Example**
```js ```js
let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE")
promise.then((tableName) => { promise.then((tableName) => {
console.info('Obtained distributed table name successfully, tableName= ' + tableName) console.info('Obtained DistributedTableName successfully, tableName= ' + tableName)
}).catch((err) => { }).catch((err) => {
console.info('Failed to obtain distributed table name, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
}) })
``` ```
...@@ -1970,9 +1864,9 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret ...@@ -1970,9 +1864,9 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret
**Example** **Example**
```js ```js
let predicates = new rdb.RdbPredicates('EMPLOYEE') let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.inDevices(['12345678abcde']) predicates.inDevices(['12345678abcde'])
rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) {
if (err) { if (err) {
console.log('Sync failed, err: ' + err) console.log('Sync failed, err: ' + err)
return return
......
# FormProvider # FormProvider
> **NOTE**<br> 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 release a widget release.
> 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.
Provides APIs related to the widget provider. > **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.
## Modules to Import ## Modules to Import
...@@ -27,11 +28,11 @@ SystemCapability.Ability.Form ...@@ -27,11 +28,11 @@ SystemCapability.Ability.Form
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- | | ------ | ------ | ---- | ------------------------------------- |
| formId | string | Yes | ID of a widget. | | formId | string | Yes | ID of a widget. |
| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. |
| 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**
...@@ -56,16 +57,16 @@ SystemCapability.Ability.Form ...@@ -56,16 +57,16 @@ SystemCapability.Ability.Form
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- | | ------ | ------ | ---- | ------------------------------------- |
| formId | string | Yes | ID of a widget. | | formId | string | Yes | ID of a widget. |
| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------- | ---------------------------------- | | ------------- | ---------------------------------- |
| Promise\<void> |Promise used to return the result. | | Promise\<void> |Promise used to return the result. |
**Example** **Example**
...@@ -90,11 +91,11 @@ SystemCapability.Ability.Form ...@@ -90,11 +91,11 @@ SystemCapability.Ability.Form
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.| | formId | string | Yes | ID of the widget to update.|
| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. |
| 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**
...@@ -121,10 +122,10 @@ SystemCapability.Ability.Form ...@@ -121,10 +122,10 @@ SystemCapability.Ability.Form
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.| | formId | string | Yes | ID of the widget to update.|
| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. |
**Return value** **Return value**
...@@ -144,3 +145,289 @@ SystemCapability.Ability.Form ...@@ -144,3 +145,289 @@ SystemCapability.Ability.Form
console.log('formProvider updateForm, error:' + JSON.stringify(error)); console.log('formProvider updateForm, error:' + JSON.stringify(error));
}); });
``` ```
## getFormsInfo<sup>9+</sup>
getFormsInfo(callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void;
Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the widget information.|
**Example**
```js
formProvider.getFormsInfo((error, data) => {
if (error.code) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}
});
```
## getFormsInfo<sup>9+</sup>
getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void;
Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| filter | formInfo.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.|
**Example**
```js
const filter : formInfo.FormInfoFilter = {
moduleName : "entry"
};
formProvider.getFormsInfo(filter, (error, data) => {
if (error.code) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}
});
```
## getFormsInfo<sup>9+</sup>
getFormsInfo(filter?: formInfo.FormInfoFilter): Promise&lt;Array&lt;formInfo.FormInfo&gt;&gt;;
Obtains the application's widget information on the device. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | No| Filter criterion.|
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Promise used to return the widget information.|
**Example**
```js
const filter : formInfo.FormInfoFilter = {
moduleName : "entry"
};
formProvider.getFormsInfo(filter).then((data) => {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
});
```
## requestPublishForm<sup>9+</sup>
requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback&lt;string&gt;): &lt;void&gt;;
Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result.
**System capability**
SystemCapability.Ability.Form
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data used for creating the widget.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Example**
```js
import formBindingData from '@ohos.application.formBindingData';
var want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry"
}
};
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.requestPublishForm(want, obj, (error, data) => {
if (error.code) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
```
## requestPublishForm<sup>9+</sup>
requestPublishForm(want: Want, callback: AsyncCallback&lt;string&gt;): &lt;void&gt;;
Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result.
**System capability**
SystemCapability.Ability.Form
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the widget ID. |
**Example**
```js
var want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry"
}
};
formProvider.requestPublishForm(want, (error, data) => {
if (error.code) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
```
## requestPublishForm<sup>9+</sup>
requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise&lt;string&gt;;
Requests to publish a widget to the widget host. This API uses a promise to return the result.
**System capability**
SystemCapability.Ability.Form
**Parameters**
| Name | Type | Mandatory| Description |
| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | No | Data used for creating the widget. |
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;string&gt; | Promise used to return the widget ID.|
**Example**
```js
var want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry"
}
};
formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
});
```
## isRequestPublishFormSupported<sup>9+<sup>
isRequestPublishFormSupported(callback: AsyncCallback&lt;boolean&gt;): void;
Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
```js
formProvider.isRequestPublishFormSupported((error, isSupported) => {
if (error.code) {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
} else {
if (isSupported) {
var want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry"
}
};
formProvider.requestPublishForm(want, (error, data) => {
if (error.code) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
}
}
});
```
## isRequestPublishFormSupported<sup>9+</sup>
isRequestPublishFormSupported(): Promise&lt;boolean&gt;;
Checks whether a widget can be published to the widget host. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.Form
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```js
formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) {
var want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry"
}
};
formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
});
}
}).catch((error) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
});
```
# Input Method Framework # Input Method Framework
> **NOTE**<br>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. > **NOTE**
> >
> 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
...@@ -21,7 +22,7 @@ Provides the constants. ...@@ -21,7 +22,7 @@ Provides the constants.
| MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| | MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.|
## InputMethodProperty<sup>8+</sup><a name="InputMethodProperty"></a> ## InputMethodProperty<sup>8+</sup>
Describes the input method application attributes. Describes the input method application attributes.
...@@ -32,7 +33,7 @@ Describes the input method application attributes. ...@@ -32,7 +33,7 @@ Describes the input method application attributes.
| packageName | string | Yes| No| Package name.| | packageName | string | Yes| No| Package name.|
| methodId | string | Yes| No| Ability name.| | methodId | string | Yes| No| Ability name.|
## inputMethod.getInputMethodController<a name="getInputMethodController"></a> ## inputMethod.getInputMethodController
getInputMethodController(): InputMethodController getInputMethodController(): InputMethodController
...@@ -48,11 +49,11 @@ Obtains an [InputMethodController](#InputMethodController) instance. ...@@ -48,11 +49,11 @@ Obtains an [InputMethodController](#InputMethodController) instance.
**Example** **Example**
```js ```js
var InputMethodController = inputMethod.getInputMethodController(); var InputMethodController = inputMethod.getInputMethodController();
``` ```
## inputMethod.getInputMethodSetting<sup>8+</sup><a name="getInputMethodSetting"></a> ## inputMethod.getInputMethodSetting<sup>8+</sup>
getInputMethodSetting(): InputMethodSetting getInputMethodSetting(): InputMethodSetting
...@@ -69,10 +70,10 @@ Obtains an [InputMethodSetting](#InputMethodSetting) instance. ...@@ -69,10 +70,10 @@ Obtains an [InputMethodSetting](#InputMethodSetting) instance.
**Example** **Example**
```js ```js
var InputMethodSetting = inputMethod.getInputMethodSetting(); var InputMethodSetting = inputMethod.getInputMethodSetting();
``` ```
## InputMethodController<a name="InputMethodController"></a> ## InputMethodController
In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance.
...@@ -120,7 +121,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ...@@ -120,7 +121,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result.
console.info('stopInput isSuccess = ' + isSuccess); console.info('stopInput isSuccess = ' + isSuccess);
``` ```
## InputMethodSetting<sup>8+</sup><a name="InputMethodSetting"></a> ## InputMethodSetting<sup>8+</sup>
In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance.
...@@ -140,18 +141,18 @@ Obtains the list of installed input methods. This API uses an asynchronous callb ...@@ -140,18 +141,18 @@ Obtains the list of installed input methods. This API uses an asynchronous callb
**Example** **Example**
```js ```js
InputMethodSetting.listInputMethod((properties)=>{ InputMethodSetting.listInputMethod((properties)=>{
for (var i = 0;i < properties.length; i++) { for (var i = 0;i < properties.length; i++) {
var property = properties[i]; var property = properties[i];
console.info(property.packageName + "/" + property.methodId); console.info(property.packageName + "/" + property.methodId);
} }
}); });
``` ```
### listInputMethod ### listInputMethod
listInputMethod(): Promise&lt;Array&lt;InputMethodProperty&gt;&gt; listInputMethod(): Array&lt;InputMethodProperty&gt;
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
...@@ -196,7 +197,7 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono ...@@ -196,7 +197,7 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono
### displayOptionalInputMethod ### displayOptionalInputMethod
displayOptionalInputMethod(): Promise&lt;void&gt; displayOptionalInputMethod(): Promise&lt;void&gt;
Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result.
......
# Settings # Settings
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -55,7 +56,7 @@ Obtains the value of a data item. ...@@ -55,7 +56,7 @@ Obtains the value of a data item.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.|
| name | string | Yes| Name of the target data item. Data items can be classified as follows:<br> <ul><li>Existing data items in the database, for example:<br></li> <ul><li>Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS<br> </li> <li>Time format: settings.date.TIME_FORMAT<br> </li></ul> <li>Custom data items</li></ul>| | name | string | Yes| Name of the target data item. Data items can be classified as follows:<br> <ul><li>Existing data items in the database, for example:<br></li> <ul><li>Brightness: **settings.display.SCREEN_BRIGHTNESS_STATUS**<br> </li> <li>Time format: **settings.date.TIME_FORMAT**<br> </li></ul> <li>Custom data items</li></ul> |
| defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.| | defValue | string | Yes| Default value This parameter is user-defined. If it is not found in the database, the default value is returned.|
**Return value** **Return value**
...@@ -93,7 +94,7 @@ If the specified data item exists in the database, the **setValueSync** method u ...@@ -93,7 +94,7 @@ If the specified data item exists in the database, the **setValueSync** method u
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.| | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes| **DataAbilityHelper** class.|
| name | string | Yes| Name of the target data item. Data items can be classified as follows:<br> <ul><li>Existing data items in the database, for example:<br></li> <ul><li>Brightness: settings.display.SCREEN_BRIGHTNESS_STATUS<br> </li> <li>Time format: settings.date.TIME_FORMAT<br> </li></ul> <li>Custom data items</li></ul>| | name | string | Yes| Name of the target data item. Data items can be classified as follows:<br> <ul><li>Existing data items in the database, for example:<br></li> <ul><li>Brightness: **settings.display.SCREEN_BRIGHTNESS_STATUS**<br> </li> <li>Time format: **settings.date.TIME_FORMAT**<br> </li></ul> <li>Custom data items</li></ul> |
| value | string | Yes| Value of the data item.| | value | string | Yes| Value of the data item.|
**Return value** **Return value**
......
# Bluetooth # Bluetooth
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br/>
> >
> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.bluetooth`](js-apis-bluetooth.md). > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.bluetooth`](js-apis-bluetooth.md).
> >
...@@ -15,7 +15,6 @@ ...@@ -15,7 +15,6 @@
import bluetooth from '@system.bluetooth'; import bluetooth from '@system.bluetooth';
``` ```
## bluetooth.startBLEScan(OBJECT) ## bluetooth.startBLEScan(OBJECT)
Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes system resources. Call [bluetooth.stopBLEScan](#bluetoothstopblescanobject) to stop the scan after a BLE device is detected and connected. Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes system resources. Call [bluetooth.stopBLEScan](#bluetoothstopblescanobject) to stop the scan after a BLE device is detected and connected.
...@@ -25,7 +24,6 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys ...@@ -25,7 +24,6 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys
**System capability**: SystemCapability.Communication.Bluetooth.Lite **System capability**: SystemCapability.Communication.Bluetooth.Lite
**Parameters** **Parameters**
**Table 1** StartBLEScanOptions **Table 1** StartBLEScanOptions
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -61,7 +59,6 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE ...@@ -61,7 +59,6 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE
**System capability**: SystemCapability.Communication.Bluetooth.Lite **System capability**: SystemCapability.Communication.Bluetooth.Lite
**Parameters** **Parameters**
**Table 2** StopBLEScanOptions **Table 2** StopBLEScanOptions
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -74,6 +71,7 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE ...@@ -74,6 +71,7 @@ Stops scanning for BLE devices nearby. This API is used with [bluetooth.startBLE
``` ```
bluetooth.stopBLEScan({ bluetooth.stopBLEScan({
interval:0,
success() { success() {
console.log('call bluetooth.stopBLEScan success.'); console.log('call bluetooth.stopBLEScan success.');
}, },
...@@ -96,7 +94,6 @@ Subscribes to the newly detected BLE device. If this API is called multiple time ...@@ -96,7 +94,6 @@ Subscribes to the newly detected BLE device. If this API is called multiple time
**System capability**: SystemCapability.Communication.Bluetooth.Lite **System capability**: SystemCapability.Communication.Bluetooth.Lite
**Parameters** **Parameters**
**Table 3** SubscribeBLEFoundOptions **Table 3** SubscribeBLEFoundOptions
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -123,7 +120,7 @@ Subscribes to the newly detected BLE device. If this API is called multiple time ...@@ -123,7 +120,7 @@ Subscribes to the newly detected BLE device. If this API is called multiple time
**Example** **Example**
``` ```
bluetooth.startaBLEScan({ bluetooth.startBLEScan({
success() { success() {
bluetooth.subscribeBLEFound({ bluetooth.subscribeBLEFound({
success(data) { success(data) {
......
...@@ -29,7 +29,7 @@ Encrypts or decrypts data using RSA. ...@@ -29,7 +29,7 @@ Encrypts or decrypts data using RSA.
| text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.|
| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| | key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.|
| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.|
| success | Function | No| Called when data is encrypted or decrypted successful.| | success | Function | No| Called when data is encrypted or decrypted successfully.|
| fail | Function | No| Called when data fails to be encrypted or decrypted.| | fail | Function | No| Called when data fails to be encrypted or decrypted.|
| complete | Function | No| Called when the execution is complete.| | complete | Function | No| Called when the execution is complete.|
...@@ -45,15 +45,18 @@ export default { ...@@ -45,15 +45,18 @@ export default {
text: 'hello', text: 'hello',
// Base64-encoded public key used for encryption. // Base64-encoded public key used for encryption.
key: key:
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' +
'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' +
'h7SoaYEeluhqFimL2AEjfSwINHCLqObJkcjCfoZpE1JCehPiDOJsyT50Auc08h/4\n' + '+Enz0RzmVFh/4yk6lmqRzuEFQqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBw\n' +
'jHQfanyC1nc62LqUCQIDAQAB', 'jBpApTJ3TeneOo6Z5QIDAQAB',
success: function(data) { success: function(data) {
console.log('handling success: ${data.text}'); console.log(`handling successful:${data.text}`);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log(`### cipher.rsa encrypt fail ### ${code}: ${data}`); console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`);
},
complete: function() {
console.log(`operation complete!`);
} }
}); });
cipher.rsa({ cipher.rsa({
...@@ -61,31 +64,33 @@ export default { ...@@ -61,31 +64,33 @@ export default {
action: 'decrypt', action: 'decrypt',
// Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello".
text: text:
'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + 'EPeCFPib6ayKbA0M6oSywARvFZ8dFYfjQv3nY8ikZGtS9UHq2sLPvAfpeIzggSiCxqbWeCftP1XQ\n' +
'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + 'Sa+jEpzFlT1qoSTunBbrYzugPTajIJDTg6R1IRsF/J+mmakn0POVPvi4jCo9wqavB324Bx0Wipnc\n' +
'S/ZWNI4Q8Q0suNjNkGU=', 'EU5WO0oBHo5l4x6dTpU=',
// Base64-encoded private key used for decryption. // Base64-encoded private key used for decryption.
key: key:
'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + 'MIICXgIBAAKBgQCx414QSP3RsYWYzf9mkBMiBAXo6S7Lpva1fKlcuVxjoFC1iMnz\n' +
'7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + 'D4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ+Enz0RzmVFh/4yk6lmqRzuEF\n' +
'aXHFEK1xQ3+HtKhpgR6W6GoWKYvYASN9LAg0cIuo5smRyMJ+hmkTUkJ6E+IM4mzJ\n' + 'QqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBwjBpApTJ3TeneOo6Z5QIDAQAB\n' +
'PnQC5zTyH/iMdB9qfILWdzrYupQJAgMBAAECgYEAkibhH0DWR13U0gvYJeD08Lfd\n' + 'AoGBAKPNtoRQcklxqo+2wQP0j2m3Qqnib1DggjVEgb/8f/LNYQSI3U2QdROemryU\n' +
'Sw1PMHyquEqIcho9Yv7bF3LOXjOg2EEGPx09mvuwXFgP1Kp1e67XPytr6pQQPzK7\n' + 'u3y6N3xacZ359PktTrRKfH5+8ohmHGhIuPAnefp6bLvAFUcl4t1xm74Cow62Kyw3\n' +
'XAPcLPx80R/ZjZs8vNFndDOd1HgD3vSVmYQarNzmKi72tOUWMPevsaFXPHo6Xx3X\n' + 'aSbmuTG98dxPA1sXD0jiprdtsq2wQ9CoKNyY7/d/pKoqxNuBAkEA4GytZ60NCTj9\n' +
'8x0wYb7XuBsQguRctTECQQD7GWX3JUiyo562iVrpTDPOXsrUxmzCrgz2OZildxMd\n' + 'w24jACFeko5YqCFY/TTLoc4SQvWtFMnimRPclLZhtUIK0P8dib71UFedx+AxklgL\n' +
'Pp/PkyDrx7mEXTpk4K/XnQJ3GpJNi2iDSxDuPSAeJ/aPAkEA4Tw4+1Z43S/xH3C3\n' + 'A5gjcfo+2QJBAMrqiwyCh3OQ5DhyRPDwt87x1/jg5fy4hhete2ufSf2FoQCVqO+w\n' +
'nfulYBNyB4si6KEUuC0krcC1pDJ21Gd12efKo5VF8SaJI1ZUQOzguV+dqNsB/JUY\n' + 'PKoljdXmJeS6rGgzGibstuHLrP3tcIho4+0CQD3ZFWzF/xq0jxKlrpWhnJuNCRfE\n' +
'OFfX5wJAB1dKv9r7MR3Peg6x9bggm5vx2h6i914XSuuMJupASM6X5X2rrLj+F3yS\n' + 'oO6e9yNvVA8J/5oEDSOcmqSNIp4+RhbUx8InUxnCG6Ryv5aSFu71pYcKrPkCQQCL\n' +
'RHi9K1SPyeOg+1tkBtKfABgRZFBOyQJAbuTivUSe73AqTKuHjB4ZF0ubqgEkJ9sf\n' + 'RUGcm3ZGTnslduB0knNF+V2ndwzDUQ7P74UXT+PjurTPhujFYiuxCEd6ORVnEOzG\n' +
'Q2rekzm9dOFvxjZGPQo1qALX09qATMi1ZN376ukby8ZAnSafLSZ64wJBAM2V37go\n' + 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' +
'Sj44HF76ksRow8gecuQm48NCTGAGTicXg8riKog2GC9y8pMNHAezoR9wXJF7kk+k\n' + '8GfqIdUNf+aCG5TZK/kXBF1sqcsi7jXMAf4jBlejVbSVZg==',
'lz5cHyoMZ9mcd30=',
success: function(data) { success: function(data) {
console.log('handling success: ${data.text}'); console.log(`handling successful:${data.text}`);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log(`### cipher.rsa decrypt fail ### ${code}: ${data}`); console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`);
}, },
complete: function() {
console.log(`operation complete!`);
}
}); });
} }
} }
...@@ -109,9 +114,9 @@ Encrypts or decrypts data using AES. ...@@ -109,9 +114,9 @@ Encrypts or decrypts data using AES.
| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| | key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.|
| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| | transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.|
| iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| | iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.|
| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**.| | ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported.|
| ivLen | string | No| Length of the IV for AES-based encryption and decryption, in bytes. The default value is **16**.| | ivLen | string | No| Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.|
| success | Function | No| Called when data is encrypted or decrypted successful.| | success | Function | No| Called when data is encrypted or decrypted successfully.|
| fail | Function | No| Called when data fails to be encrypted or decrypted.| | fail | Function | No| Called when data fails to be encrypted or decrypted.|
| complete | Function | No| Called when the execution is complete.| | complete | Function | No| Called when the execution is complete.|
...@@ -128,35 +133,38 @@ export default { ...@@ -128,35 +133,38 @@ export default {
// Base64-encoded key used for encryption. // Base64-encoded key used for encryption.
key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
transformation: 'AES/CBC/PKCS5Padding', transformation: 'AES/CBC/PKCS5Padding',
ivOffset: 0, ivOffset: '0',
ivLen: 16, ivLen: '16',
success: (data) => { success: function(data) {
console.log('handling success: ${data.text}'); console.log(`handling successful:${data.text}`);
},
fail: function(data, code) {
console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`);
}, },
fail: (data, code) => { complete: function() {
console.log(`### cipher.aes encrypt fail ### ${code}: ${data}`); console.log(`operation complete!`);
} }
}); });
cipher.aes({ cipher.aes({
// Decrypt data. // Decrypt data.
action: 'decrypt', action: 'decrypt',
// Text to be decrypted, which is binary text encoded in Base64. // Text to be decrypted, which is binary text encoded in Base64.
text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + text: '1o0kf2HXwLxHkSh5W5NhzA==',
'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' +
'S/ZWNI4Q8Q0suNjNkGU=',
// Base64-encoded key used for decryption. // Base64-encoded key used for decryption.
key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
transformation: 'AES/CBC/PKCS5Padding', transformation: 'AES/CBC/PKCS5Padding',
ivOffset: 0, ivOffset: '0',
ivLen: 16, ivLen: '16',
success: (data) => { success: function(data) {
this.dealTxt = data.text; console.log(`handling success:${data.text}`);
}, },
fail: (data, code) => { fail: function(data, code) {
prompt.showToast({ console.log(`### Failed to decrypt cipher.rsa ### ${code}:${data}`);
message: (`### cipher.aes decrypt fail ### code = ${code}: ${data}`)
})
}, },
complete: function() {
console.log(`operation complete!`);
}
});
}); });
} }
} }
......
# video # video
> **NOTE**<br> > **NOTE**
> >
> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
> >
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
> ] > ]
> ``` > ```
The **\<Video>** component provides a video player. The **\<video>** component provides a video player.
## Child Components ## Child Components
...@@ -76,7 +76,8 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ...@@ -76,7 +76,8 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
| pause | - | Pauses a video.| | pause | - | Pauses a video.|
| setCurrentTime | {&nbsp;currenttime:&nbsp;value&nbsp;} | Sets the video playback position, in seconds.| | setCurrentTime | {&nbsp;currenttime:&nbsp;value&nbsp;} | Sets the video playback position, in seconds.|
> **NOTE**<br> > **NOTE**
>
> The methods in the above table can be called after the **attached** callback is invoked. > The methods in the above table can be called after the **attached** callback is invoked.
## Example ## Example
...@@ -89,7 +90,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ...@@ -89,7 +90,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
onpaues='pauesCallback' onfinish='finishCallback' onerror='errorCallback' onpaues='pauesCallback' onfinish='finishCallback' onerror='errorCallback'
onseeking='seekingCallback' onseeked='seekedCallback' onseeking='seekingCallback' onseeked='seekedCallback'
ontimeupdate='timeupdateCallback' ontimeupdate='timeupdateCallback'
style="object-fit:fit; width:80%; height:400px;" style="object-fit:fill; width:80%; height:400px;"
onclick="change_start_pause"> onclick="change_start_pause">
</video> </video>
</div> </div>
......
# Progress # Progress
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Progress&gt;** component is used to provide a progress bar that displays the progress of content loading or an operation. The **\<Progress>** component is used to provide a progress bar that displays the progress of content loading or an operation.
## Required Permissions ## Required Permissions
...@@ -15,12 +16,12 @@ None ...@@ -15,12 +16,12 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
Progress(value: { value: number, total?: number, type?: ProgressType}) Progress(value: {value: number, total?: number, type?: ProgressType})
Creates a progress bar. Creates a progress bar.
...@@ -54,7 +55,8 @@ Creates a progress bar. ...@@ -54,7 +55,8 @@ Creates a progress bar.
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ProgressExample { struct ProgressExample {
...@@ -88,8 +90,8 @@ struct ProgressExample { ...@@ -88,8 +90,8 @@ struct ProgressExample {
Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) { Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Capsule }).width(100) Progress({ value: 10, type: ProgressType.Capsule }).width(100).height(50)
Progress({ value: 20, total: 150, type: ProgressType.Capsule }).color(Color.Grey).value(50).width(100) Progress({ value: 20, total: 150, type: ProgressType.Capsule }).color(Color.Grey).value(50).width(100).height(50)
} }
}.width('100%').margin({ top: 30 }) }.width('100%').margin({ top: 30 })
} }
......
# TextArea # TextArea
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -15,12 +16,12 @@ None ...@@ -15,12 +16,12 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
TextArea(value?:{placeholder?: string controller?: TextAreaController}) TextArea(value?:{placeholder?: string, controller?: TextAreaController})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
...@@ -93,10 +94,11 @@ Sets the position of the caret. ...@@ -93,10 +94,11 @@ Sets the position of the caret.
@Entry @Entry
@Component @Component
struct TextAreaExample1 { struct TextAreaExample1 {
controller: TextAreaController = new TextAreaController()
@State text: string = '' @State text: string = ''
build() { build() {
Column() { Column() {
TextArea({ placeholder: 'input your word'}) TextArea({ placeholder: 'input your word', controller: this.controller})
.placeholderColor("rgb(0,0,225)") .placeholderColor("rgb(0,0,225)")
.placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic }) .placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic })
.textAlign(TextAlign.Center) .textAlign(TextAlign.Center)
...@@ -112,6 +114,7 @@ struct TextAreaExample1 { ...@@ -112,6 +114,7 @@ struct TextAreaExample1 {
}) })
.onChange((value: string) => { .onChange((value: string) => {
this.text = value this.text = value
this.controller.caretPosition(-1)
}) })
Text(this.text).width('90%') Text(this.text).width('90%')
} }
......
# TextInput # TextInput
> **NOTE**<br/> > **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -14,7 +15,7 @@ None ...@@ -14,7 +15,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -39,7 +40,7 @@ In addition to universal attributes, the following attributes are supported. ...@@ -39,7 +40,7 @@ In addition to universal attributes, the following attributes are supported.
| placeholderFont | {<br/>size?: Length,<br/>weight?: number\|[FontWeight](ts-universal-attributes-text-style.md),<br/>family?: string,<br/>style?: [FontStyle](ts-universal-attributes-text-style.md)<br/>} | - | Placeholder text style.<br/>- **size**: font size. If the value is of the number type, the unit fp is used.<br/>- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.<br/>- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.<br/>- **style**: font style. | | placeholderFont | {<br/>size?: Length,<br/>weight?: number\|[FontWeight](ts-universal-attributes-text-style.md),<br/>family?: string,<br/>style?: [FontStyle](ts-universal-attributes-text-style.md)<br/>} | - | Placeholder text style.<br/>- **size**: font size. If the value is of the number type, the unit fp is used.<br/>- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.<br/>- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.<br/>- **style**: font style. |
| enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. | | enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. |
| caretColor | Color | - | Color of the caret (also known as the text insertion cursor). | | caretColor | Color | - | Color of the caret (also known as the text insertion cursor). |
| maxLength<sup>8+</sup> | number | - | Maximum number of characters in the text input. | | maxLength | number | - | Maximum number of characters in the text input. |
| inputFilter<sup>8+</sup> | {<br/>value: [ResourceStr](../../ui/ts-types.md)<sup>8+</sup>,<br/>error?: (value: string)<br/>} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(? =.\*\d)(? =.\*[a-z])(? =.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br/>- **value**: regular expression to set.<br/>- **error**: error message containing the ignored content returned when regular expression matching fails. | | inputFilter<sup>8+</sup> | {<br/>value: [ResourceStr](../../ui/ts-types.md)<sup>8+</sup>,<br/>error?: (value: string)<br/>} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(? =.\*\d)(? =.\*[a-z])(? =.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br/>- **value**: regular expression to set.<br/>- **error**: error message containing the ignored content returned when regular expression matching fails. |
| copyOption<sup>9+</sup> | boolean\|[CopyOption](ts-basic-components-text.md) | true | Whether copy and paste is allowed. | | copyOption<sup>9+</sup> | boolean\|[CopyOption](ts-basic-components-text.md) | true | Whether copy and paste is allowed. |
...@@ -75,10 +76,10 @@ In addition to universal attributes, the following attributes are supported. ...@@ -75,10 +76,10 @@ In addition to universal attributes, the following attributes are supported.
### TextInputController<sup>8+</sup> ### TextInputController<sup>8+</sup>
Implements the controller of the **&lt;TextInput&gt;** component. Implements the controller of the **\<TextInput>** component.
### Objects to Import #### Objects to Import
``` ```
...@@ -86,7 +87,7 @@ controller: TextInputController = new TextInputController() ...@@ -86,7 +87,7 @@ controller: TextInputController = new TextInputController()
``` ```
### caretPosition #### caretPosition
caretPosition(value: number): void caretPosition(value: number): void
...@@ -113,10 +114,9 @@ struct TextInputExample1 { ...@@ -113,10 +114,9 @@ struct TextInputExample1 {
build() { build() {
Column() { Column() {
TextArea({ placeholder: 'input your word' }) TextInput({ placeholder: 'input your word' })
.placeholderColor("rgb(0,0,225)") .placeholderColor("rgb(0,0,225)")
.placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic }) .placeholderFont({ size: 30, weight: 100, family: 'cursive', style: FontStyle.Italic })
.textAlign(TextAlign.Center)
.caretColor(Color.Blue) .caretColor(Color.Blue)
.height(50) .height(50)
.fontSize(30) .fontSize(30)
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;GridContainer&gt;** component lays out components vertically. It is used only in the grid layout. The **<GridContainer\>** component lays out components vertically. It is used only in the grid layout.
## Required Permissions ## Required Permissions
...@@ -33,7 +33,7 @@ GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter ...@@ -33,7 +33,7 @@ GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter
- SizeType enums - SizeType enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| XS | Device of the minimum size. | | XS | Minimum-sized device. |
| SM | Small-sized device. | | SM | Small-sized device. |
| MD | Medium-sized device. | | MD | Medium-sized device. |
| LG | Large-sized device. | | LG | Large-sized device. |
...@@ -42,7 +42,7 @@ GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter ...@@ -42,7 +42,7 @@ GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter
## Attributes ## Attributes
Universal attributes and [attributes](ts-container-column.md#attributes) of the **&lt;Column&gt;** component are supported. Universal attributes and [attributes](ts-container-column.md#attributes) of the **<Column\>** component are supported.
## Events ## Events
......
# Navigator # Navigator
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **Navigator** component provides redirection to the target page. The **\<Navigator>** component provides redirection to the target page.
## Required Permissions ## Required Permissions
...@@ -42,25 +43,26 @@ Creates a navigator. ...@@ -42,25 +43,26 @@ Creates a navigator.
| Name | Parameters | Default Value | Description | | Name | Parameters | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| active | boolean | - | Whether the **Navigator** component is activated. If the component is activated, the corresponding navigation takes effect. | | active | boolean | - | Whether the **\<Navigator>** component is activated. If the component is activated, the corresponding navigation takes effect. |
| params | Object | undefined | Data that needs to be passed to the target page during redirection. You can use **router.getParams()** to obtain the data on the target page. | | params | Object | undefined | Data that needs to be passed to the target page during redirection. You can use **router.getParams()** to obtain the data on the target page. |
## Example ## Example
``` ```ts
// Navigator Page // Navigator.ets
@Entry @Entry
@Component @Component
struct NavigatorExample { struct NavigatorExample {
@State active: boolean = false @State active: boolean = false
@State Text: string = 'news' @State Text: object = {name: 'news'}
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Navigator({ target: 'pages/container/navigator/Detail', type: NavigationType.Push }) { Navigator({ target: 'pages/container/navigator/Detail', type: NavigationType.Push }) {
Text('Go to ' + this.Text + ' page').width('100%').textAlign(TextAlign.Center) Text('Go to ' + this.Text['name'] + ' page')
.width('100%').textAlign(TextAlign.Center)
}.params({ text: this.Text }) }.params({ text: this.Text })
Navigator() { Navigator() {
...@@ -75,14 +77,14 @@ struct NavigatorExample { ...@@ -75,14 +77,14 @@ struct NavigatorExample {
``` ```
``` ```ts
// Detail Page // Detail.ets
import router from '@system.router' import router from '@system.router'
@Entry @Entry
@Component @Component
struct DetailExample { struct DetailExample {
@State text: string = router.getParams().text @State text: any = router.getParams().text
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
...@@ -90,7 +92,8 @@ struct DetailExample { ...@@ -90,7 +92,8 @@ struct DetailExample {
Text('Go to back page').width('100%').height(20) Text('Go to back page').width('100%').height(20)
} }
Text('This is ' + this.text + ' page').width('100%').textAlign(TextAlign.Center) Text('This is ' + this.text['name'] + ' page')
.width('100%').textAlign(TextAlign.Center)
} }
.width('100%').height(200).padding({ left: 35, right: 35, top: 35 }) .width('100%').height(200).padding({ left: 35, right: 35, top: 35 })
} }
...@@ -98,9 +101,8 @@ struct DetailExample { ...@@ -98,9 +101,8 @@ struct DetailExample {
``` ```
```ts
``` // Back.ets
// Back Page
@Entry @Entry
@Component @Component
struct BackExample { struct BackExample {
......
# Panel # Panel
> **NOTE** > **NOTE**<br>
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -26,7 +25,7 @@ Panel(value:{show:boolean}) ...@@ -26,7 +25,7 @@ Panel(value:{show:boolean})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| show | boolean | Yes | - | Whether the panel is shown or hidden. | | show | boolean | Yes | - | Whether to show or hide the panel. |
## Attributes ## Attributes
...@@ -35,7 +34,7 @@ Panel(value:{show:boolean}) ...@@ -35,7 +34,7 @@ Panel(value:{show:boolean})
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | PanelType | PanelType.Foldable | Type of the panel. | | type | PanelType | PanelType.Foldable | Type of the panel. |
| mode | PanelMode | - | Initial status of the panel. | | mode | PanelMode | - | Initial status of the panel. |
| dragBar | boolean | true | Whether to enable a drag bar. The value **true** means that the drag bar will be displayed, and **false** means the opposite. | | dragBar | boolean | true | Whether to enable a drag bar. The value **true** means to display the drag bar, and **false** means the opposite. |
| fullHeight | Length | - | Panel height in the **PanelMode.Full** mode. | | fullHeight | Length | - | Panel height in the **PanelMode.Full** mode. |
| halfHeight | Length | - | Panel height in the **PanelMode.Half** mode. The default value is half of the screen height. | | halfHeight | Length | - | Panel height in the **PanelMode.Half** mode. The default value is half of the screen height. |
| miniHeight | Length | - | Panel height in the **PanelMode.Mini** mode. | | miniHeight | Length | - | Panel height in the **PanelMode.Mini** mode. |
...@@ -59,7 +58,7 @@ Panel(value:{show:boolean}) ...@@ -59,7 +58,7 @@ Panel(value:{show:boolean})
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onChange(callback: (width: number, height: number, mode: PanelMode) =&gt; void) | Triggered when the status of the panel changes. The returned height value is the height of the content area. When the value of **dragbar** is **true**, the height of the panel is the drag bar height plus the height of the content area. | | onChange(callback: (width: number, height: number, mode: PanelMode) =&gt; void) | Triggered when the panel status changes. The returned height value is the height of the content area. When the value of **dragbar** is **true**, the height of the panel is the drag bar height plus the height of the content area. |
## Example ## Example
......
...@@ -23,7 +23,7 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number\}\) ...@@ -23,7 +23,7 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number\}\)
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| refreshing | boolean | Yes| - | Whether the current component is being refreshed. | | refreshing | boolean | Yes| - | Whether the current component is being refreshed. |
| offset | Length | No| 16 | Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture. | | offset | Length | No| 16 | Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture. |
| friction | number | No| 62 | Coefficient of friction, which indicates the **<Refresh\>** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100. <br/>- **0** indicates that the **<Refresh\>** component is not sensitive to the pull-down gesture. <br/>- **100** indicates that the **<Refresh\>** component is highly sensitive to the pull-down gesture. <br/>- A larger value indicates a more sensitive response of the **<Refresh\>** component to the pull-down gesture. | | friction | number | No| 62 | Coefficient of friction, which indicates the **<Refresh\>** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100. <br/>- **0**: The **<Refresh\>** component is not sensitive to the pull-down gesture. <br/>- **100**: The **<Refresh\>** component is highly sensitive to the pull-down gesture. <br/>- Value greater than **100**: The **<Refresh\>** component is much more sensitive to the pull-down gesture. |
...@@ -32,8 +32,8 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number\}\) ...@@ -32,8 +32,8 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number\}\)
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes. <br/>**state** indicates the refresh status.| | onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes. <br/>**state** indicates the refresh status. |
| onRefreshing(callback: () => void)| Triggered when the component enters the refresh state.| | onRefreshing(callback: () => void)| Triggered when the component enters the refresh state. |
- RefreshStatus enums - RefreshStatus enums
......
...@@ -22,17 +22,17 @@ Supported ...@@ -22,17 +22,17 @@ Supported
Row(value:{space?: Length}) Row(value:{space?: Length})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| space | Length | No| 0 | Space between two adjacent child components in the horizontal layout. | | space | Length | No| 0 | Space between two adjacent child components in the horizontal layout. |
## Attributes ## Attributes
| Name| Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| alignItems | VerticalAlign | VerticalAlign.Center | Alignment mode of child components in the vertical direction. | | alignItems | VerticalAlign | VerticalAlign.Center | Alignment mode of the child components in the vertical direction. |
| justifyContent8+ | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | Alignment mode of child components in the horizontal direction. | | justifyContent8+ | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | Alignment mode of the child components in the horizontal direction. |
- VerticalAlign enums - VerticalAlign enums
| Name | Description | | Name | Description |
......
...@@ -27,7 +27,7 @@ RowSplit() ...@@ -27,7 +27,7 @@ RowSplit()
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| resizeable | boolean | Whether the divider can be dragged. The default value is **false**. | | resizeable | boolean | Whether the divider is draggable. The default value is **false**. |
> **NOTE**<br> > **NOTE**<br>
> Similar to **<RowSplit\>**, the divider of **<RowSplit\>** can be dragged to a position that just fully holds a component. > Similar to **<RowSplit\>**, the divider of **<RowSplit\>** can be dragged to a position that just fully holds a component.
......
# Scroll # Scroll
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Scroll&gt;** component scrolls the content when the layout size of a component exceeds the viewport of its parent component. The **<Scroll\>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
## Required Permissions ## Required Permissions
...@@ -42,7 +42,7 @@ Scroll(scroller?: Scroller) ...@@ -42,7 +42,7 @@ Scroll(scroller?: Scroller)
## Scroller ## Scroller
Controller of the scrollable container component. You can bind this component to the container component and use it to control the scrolling of the container component. Currently, this component can be bound to the **&lt;List&gt;** and **&lt;Scroll&gt;** components. Controller of the scrollable container component. You can bind this component to the container component and use it to control the scrolling of the container component. Currently, this component can be bound to the **<List\>** and **<Scroll\>** components.
### Objects to Import ### Objects to Import
...@@ -106,7 +106,7 @@ Obtains the scrolling offset. ...@@ -106,7 +106,7 @@ Obtains the scrolling offset.
- Return value - Return value
| Type | Description | | Type | Description |
| -------- | -------- | | -------- | -------- |
| {<br/>xOffset: number,<br/>yOffset: number<br/>} | **xOffset**: horizontal scrolling offset.<br/>**yOffset**: vertical scrolling offset. | | {<br/>xOffset: number,<br/>yOffset: number<br/>} | - **xOffset**: horizontal scrolling offset.<br/>- **yOffset**: vertical scrolling offset. |
### scroller.scrollToIndex ### scroller.scrollToIndex
...@@ -117,8 +117,8 @@ scroller.scrollToIndex(value: number): void ...@@ -117,8 +117,8 @@ scroller.scrollToIndex(value: number): void
Scrolls to the specified index. Scrolls to the specified index.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> Only the **&lt;List&gt;** component is supported. > Only the **<List\>** component is supported.
- Parameters - Parameters
...@@ -131,8 +131,8 @@ Scrolls to the specified index. ...@@ -131,8 +131,8 @@ Scrolls to the specified index.
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | | onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical scrolling offsets when the specified scroll event occurs. |
| onScrollEdge(side: Edge) =&gt; void | Callback for the event of scrolling to the edge. | | onScrollEdge(side: Edge) =&gt; void | Invoked when an item is scrolled to the edge. |
| onScrollEnd() =&gt; void | Invoked when scrolling stops. | | onScrollEnd() =&gt; void | Invoked when scrolling stops. |
......
# Stack # Stack
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Stack&gt;** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one. The **<Stack\>** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
## Required Permissions ## Required Permissions
......
# Swiper # Swiper
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Swiper&gt;** component provides a container that allows users to switch among child components by swiping operations. The **<Swiper\>** component provides a container that allows users to switch among child components through swiping.
## Required Permissions ## Required Permissions
...@@ -42,14 +42,14 @@ Swiper(value:{controller?: SwiperController}) ...@@ -42,14 +42,14 @@ Swiper(value:{controller?: SwiperController})
| itemSpace | Length | 0 | Space between child components. | | itemSpace | Length | 0 | Space between child components. |
| cachedCount<sup>8+</sup> | number | 1 | Number of child components to be cached. | | cachedCount<sup>8+</sup> | number | 1 | Number of child components to be cached. |
| disableSwipe<sup>8+</sup> | boolean | false | Whether to disable the swipe feature. | | disableSwipe<sup>8+</sup> | boolean | false | Whether to disable the swipe feature. |
| curve<sup>8+</sup> | [Curve](ts-animatorproperty.md) \| Curves | Curve.Ease | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve enums](ts-animatorproperty.md). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module. | | curve<sup>8+</sup> | [Curve](ts-animatorproperty.md) \| Curves | Curve.Ease | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve enums](ts-animatorproperty.md). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using APIs provided by the interpolation calculation module. |
### SwiperController ### SwiperController
Controller of the **&lt;Swiper&gt;** component. You can bind this object to the **&lt;Swiper&gt;** component and use it to control page switching. Controller of the **<Swiper\>** component. You can bind this object to the **<Swiper\>** component and use it to control page switching.
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| showNext():void | Turns to the next page. | | showNext():void | Turns to the next page. |
| showPrevious():void | Turns to the previous page. | | showPrevious():void | Turns to the previous page. |
...@@ -57,7 +57,7 @@ Controller of the **&lt;Swiper&gt;** component. You can bind this object to the ...@@ -57,7 +57,7 @@ Controller of the **&lt;Swiper&gt;** component. You can bind this object to the
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| onChange( index: number) =&gt; void | Triggered when the index of the currently displayed component changes. | | onChange( index: number) =&gt; void | Triggered when the index of the currently displayed component changes. |
......
# TabContent # TabContent
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;TabContent&gt;** component is used only in the **&lt;Tabs&gt;** component. It corresponds to the content view of a switched tab page. The **<TabContent\>** component is used only in the **<Tabs\>** component. It corresponds to the content view of a switched tab page.
## Required Permissions ## Required Permissions
...@@ -29,12 +29,12 @@ Touch target configuration is not supported. ...@@ -29,12 +29,12 @@ Touch target configuration is not supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| tabBar | string \| {<br/>icon?: string,<br/>text?: string<br/>}<br/>\| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Content displayed on the tab bar.<br/>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. | | tabBar | string \| {<br/>icon?: string,<br/>text?: string<br/>}<br/>\| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Content displayed on the tab bar.<br/>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 or later).<br/>**NOTE**<br/>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> - The **&lt;TabContent&gt;** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **&lt;Tabs&gt;** component. > - The **<TabContent\>** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **<Tabs\>** component.
> >
> - The **&lt;TabContent&gt;** component does not support setting of the common height attribute. Its height is determined by the height of the parent **&lt;Tabs&gt;** component and the **&lt;TabBar&gt;** component. > - The **<TabContent\>** component does not support setting of the common height attribute. Its height is determined by the height of the parent **<Tabs\>** component and the **<TabBar\>** component.
## Example ## Example
......
# Tabs # Tabs
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Tabs&gt;** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view. The **<Tabs\>** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view.
## Required Permissions ## Required Permissions
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## Child Components ## Child Components
The **&lt;Tabs&gt;** component can contain [TabContent](ts-container-tabcontent.md) child components. A **<Tabs\>** component can contain multiple [TabContent](ts-container-tabcontent.md) components.
## APIs ## APIs
...@@ -25,7 +25,7 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro ...@@ -25,7 +25,7 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| barPosition | BarPosition | No | BarPosition.Start | Tab bar position for creating the **&lt;Tabs&gt;** container component. | | barPosition | BarPosition | No | BarPosition.Start | Tab bar position for creating the **<Tabs\>** container component. |
| index | number | No | 0 | Initial tab index. | | index | number | No | 0 | Initial tab index. |
| controller | [TabsController](#tabscontroller) | No | - | Tab controller. | | controller | [TabsController](#tabscontroller) | No | - | Tab controller. |
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Circle&gt;** component is used to draw a circle. The **<Circle\>** component is used to draw a circle.
## Required Permissions ## Required Permissions
...@@ -25,7 +25,7 @@ Circle(options?: {width: Length, height: Length}) ...@@ -25,7 +25,7 @@ Circle(options?: {width: Length, height: Length})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the circle to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Ellipse&gt;** component is used to draw an ellipse. The **<Ellipse\>** component is used to draw an ellipse.
## Required Permissions ## Required Permissions
...@@ -25,13 +25,13 @@ ellipse(options?: {width: Length, height: Length}) ...@@ -25,13 +25,13 @@ ellipse(options?: {width: Length, height: Length})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the ellipse to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. | | width | Length | Yes | - | Width of the ellipse. |
| height | Length | Yes | - | Height. | | height | Length | Yes | - | Height of the ellipse. |
## Attributes ## Attributes
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Line&gt;** component is used to draw a straight line. The **<Line\>** component is used to draw a straight line.
## Required Permissions ## Required Permissions
...@@ -25,13 +25,13 @@ Line(options?: {width: Length, height: Length}) ...@@ -25,13 +25,13 @@ Line(options?: {width: Length, height: Length})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the line to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. | | width | Length | Yes | - | Line width. |
| height | Length | Yes | - | Height. | | height | Length | Yes | - | Line height. |
## Attributes ## Attributes
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Path&gt;** component is used to draw a path. The **<Path\>** component is used to draw a path.
## Required Permissions ## Required Permissions
...@@ -24,7 +24,7 @@ None ...@@ -24,7 +24,7 @@ None
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | 0 | No | Width of the rectangle where the path is located. | | width | Length | 0 | No | Width of the rectangle where the path is located. |
| height | Length | 0 | No | Height of the rectangle where the path is located. | | height | Length | 0 | No | Height of the rectangle where the path is located. |
| commands | string | '' | Yes | Command string for drawing the path. | | commands | string | '' | Yes | Commands for drawing the path. |
The supported commands are as follows: The supported commands are as follows:
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Polygon&gt;** component is used to draw a polygon. The **<Polygon\>** component is used to draw a polygon.
## Required Permissions ## Required Permissions
...@@ -25,13 +25,13 @@ Polygon(value:{options?: {width: Length, height: Length}}) ...@@ -25,13 +25,13 @@ Polygon(value:{options?: {width: Length, height: Length}})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the polygon to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. | | width | Length | Yes | - | Width of the polygon. |
| height | Length | Yes | - | Height. | | height | Length | Yes | - | Height of the polygon. |
## Attributes ## Attributes
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Polyline&gt;** component is used to draw a polyline. The **<Polyline\>** component is used to draw a polyline.
## Required Permissions ## Required Permissions
...@@ -25,13 +25,13 @@ Polyline(options?: {width: Length, height: Length}) ...@@ -25,13 +25,13 @@ Polyline(options?: {width: Length, height: Length})
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the polyline to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. | | width | Length | Yes | - | Width of the polyline. |
| height | Length | Yes | - | Height. | | height | Length | Yes | - | Height of the polyline. |
## Attributes ## Attributes
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Rect&gt;** component is used to draw a rectangle. The **<Rect\>** component is used to draw a rectangle.
## Required Permissions ## Required Permissions
...@@ -25,14 +25,14 @@ Rect(value:{options?: {width: Length,height: Length,radius?: Length | Array&lt;L ...@@ -25,14 +25,14 @@ Rect(value:{options?: {width: Length,height: Length,radius?: Length | Array&lt;L
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | - | Options of the rectangle to draw. For details, see the **options** parameters. |
- options parameters - options parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. | | width | Length | Yes | - | Width of the rectangle. |
| height | Length | Yes | - | Height. | | height | Length | Yes | - | Height of the rectangle. |
| radius | Length \| Array&lt;Length&gt; | No | 0 | Radius of a rounded corner. You can set the radius of four rounded corners. | | radius | Length \| Array&lt;Length&gt; | No | 0 | Radius of the rounded corner. You can set the radius of four rounded corners. |
| radiusWidth | Length | No | 0 | Width of the rounded corner. | | radiusWidth | Length | No | 0 | Width of the rounded corner. |
| radiusHeight | Length | No | 0 | Height of the rounded corner. | | radiusHeight | Length | No | 0 | Height of the rounded corner. |
...@@ -41,11 +41,11 @@ Rect(value:{options?: {width: Length,height: Length,radius?: Length | Array&lt;L ...@@ -41,11 +41,11 @@ Rect(value:{options?: {width: Length,height: Length,radius?: Length | Array&lt;L
| Name | Type | Default Value | Mandatory | Description | | Name | Type | Default Value | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | Length | 0 | No | Width. | | width | Length | 0 | No | Width of the rectangle. |
| height | Length | 0 | No | Height. | | height | Length | 0 | No | Height of the rectangle. |
| radiusWidth | Length | 0 | No | Width of a rounded corner. The width and height are the same when only the width is set. | | radiusWidth | Length | 0 | No | Width of the rounded corner. The width and height are the same when only the width is set. |
| radiusHeight | Length | 0 | No | Height of the rounded corner. The width and height are the same only when the height is set. | | radiusHeight | Length | 0 | No | Height of the rounded corner. The width and height are the same only when the height is set. |
| radius | Length \| Array&lt;Length&gt; | 0 | No | Size of the rounded corner. | | radius | Length \| Array&lt;Length&gt; | 0 | No | Radius of the rounded corner. |
## Example ## Example
......
...@@ -5,13 +5,13 @@ ...@@ -5,13 +5,13 @@
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Shape&gt;** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components. The **<Shape\>** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components.
1. The drawing components use **&lt;Shape&gt;** as the parent component to implement the effect similar to SVG. 1. Drawing components use **<Shape\>** as their parent component to implement the effect similar to SVG.
2. The **&lt;Shape&gt;** component is used independently to draw a specific shape. 2. The **<Shape\>** component is used independently to draw a specific shape.
## Required Permissions ## Required Permissions
......
...@@ -19,15 +19,15 @@ Use the following attributes to bind gesture recognition to a component. When a ...@@ -19,15 +19,15 @@ Use the following attributes to bind gesture recognition to a component. When a
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| gesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting. | | gesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting. |
| priorityGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to preferentially recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> - By default, the child component takes precedence over the parent component in gesture recognition. When **priorityGesture** is configured for the parent component, the parent component takes precedence over the child component in gesture recognition. | | priorityGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to preferentially recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>**NOTE**<br/>By default, the child component takes precedence over the parent component in gesture recognition. When **priorityGesture** is configured for the parent component, the parent component takes precedence over the child component in gesture recognition. |
| parallelGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> - The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect. | | parallelGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>**NOTE**<br/>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect. |
- GestureMask enums - GestureMask enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence. | | Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence. |
| IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> However, the built-in gestures of the child components are not masked. For example, when the child component is a **&lt;List&gt;** component, the built-in sliding gestures can still be triggered. | | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.<br/>**NOTE**<br/>The built-in gestures of the child components are not masked. For example, when the child component is a **&lt;List&gt;** component, the built-in sliding gestures can still be triggered. |
- GestureType enums - GestureType enums
...@@ -43,7 +43,7 @@ Use the following attributes to bind gesture recognition to a component. When a ...@@ -43,7 +43,7 @@ Use the following attributes to bind gesture recognition to a component. When a
## Gesture Response Event ## Gesture Response Event
The component uses the **gesture** method to bind the gesture object and uses the events provided in this object to respond to the gesture operation. For example, the **onAction** event of the **TapGesture** object can be used to respond to a click event. For details about the event definition, see the section of each gesture object. The component uses the **gesture** method to bind the gesture object and uses the events provided in this object to respond to the gesture operation. For example, the **onAction** event of the **TapGesture** object can be used to respond to a click event. For details about the events, see the section of each gesture object.
- TapGesture events - TapGesture events
| Name | Description | | Name | Description |
......
# Interpolation Calculation # Interpolation Calculation
> **NOTE**<br> > **NOTE**<br>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -20,12 +21,12 @@ init(curve?: Curve): Object ...@@ -20,12 +21,12 @@ init(curve?: Curve): Object
Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ----- | ----- | --------- | ------------- | ------------- | | -------- | -------- | -------- | -------- | -------- |
| curve | Curve | No | Linear | Curve object. | | curve | Curve | No | Linear | Curve object. |
- Return value - Return value<br>
Curve object. Curve object.
## curves.steps ## curves.steps
...@@ -35,10 +36,11 @@ steps(count: number, end: boolean): Object ...@@ -35,10 +36,11 @@ steps(count: number, end: boolean): Object
Constructs a step curve object. Constructs a step curve object.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| count | number | Yes | - | Number of steps. Must be a positive integer. | | count | number | Yes | - | Number of steps. The value must be a positive integer. |
| end | boolean | Yes | true | Step change at the start or end point of each interval. Defaults to **true**, indicating that the step change occurs at the end point. | | end | boolean | No | true | Step change at the start or end point of each interval. Defaults to **true**, indicating that the step change occurs at the end point. |
- Return value - Return value
...@@ -51,6 +53,7 @@ cubicBezier(x1: number, y1: number, x2: number, y2: number): Object ...@@ -51,6 +53,7 @@ cubicBezier(x1: number, y1: number, x2: number, y2: number): Object
Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. Constructs a third-order Bezier curve object. The curve value must be between 0 and 1.
1. Parameters 1. Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | --------- | -------------------------------------------------------------- | | ---- | ------ | --------- | -------------------------------------------------------------- |
| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve. | | x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve. |
...@@ -69,6 +72,7 @@ spring(velocity: number, mass: number, stiffness: number, damping: number): Obje ...@@ -69,6 +72,7 @@ spring(velocity: number, mass: number, stiffness: number, damping: number): Obje
Constructs a spring curve object. Constructs a spring curve object.
1. Parameters 1. Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | --------- | ----------------- | | --------- | ------ | --------- | ----------------- |
| velocity | number | Yes | Initial velocity. | | velocity | number | Yes | Initial velocity. |
......
# Action Sheet # Action Sheet
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -32,9 +32,8 @@ Defines and shows the action sheet. ...@@ -32,9 +32,8 @@ Defines and shows the action sheet.
| sheets | Array&lt;SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. | | sheets | Array&lt;SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
- SheetInfo parameters - SheetInfo parameters
| | | | | |
| -------- | -------- | -------- | -------- | -------- |
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string | Yes | - | Sheet text. | | title | string | Yes | - | Sheet text. |
| icon | string | No | None | Sheet icon. | | icon | string | No | None | Sheet icon. |
| action | ()=&gt;void | Yes | - | Callback when the sheet is selected. | | action | ()=&gt;void | Yes | - | Callback when the sheet is selected. |
......
# Alert Dialog Box # Alert Dialog Box
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
You can set the text content and response callback for an alert dialog box. The **<AlertDialog\>** component is used to display an alert dialog box. You can set the text content and response callback for an alert dialog box as needed.
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| show | options: { paramObject1\| paramObject2} | - | Defines and displays the **&lt;AlertDialog&gt;** component. | | show | options: { paramObject1\| paramObject2} | - | Defines and displays the **<AlertDialog\>** component. |
- paramObject1 parameters - paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **CustomDialogController** class is used to display a custom dialog box. A custom dialog box is a dialog box you customize by using APIs of the **CustomDialogController** class.
## APIs ## APIs
...@@ -27,9 +27,9 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, aut ...@@ -27,9 +27,9 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, aut
- DialogAlignment enums - DialogAlignment enums
| Name | Description | | Name | Description |
| -------- | -------- | | -------- | -------- |
| Top | Aligns vertically to the top. | | Top | Vertical top alignment. |
| Center | Aligns vertically to the middle. | | Center | Vertical center alignment. |
| Bottom | Aligns vertically to the bottom. | | Bottom | Vertical bottom alignment. |
| Default | Default alignment. | | Default | Default alignment. |
| TopStart<sup>8+</sup> | Top left alignment. | | TopStart<sup>8+</sup> | Top left alignment. |
| TopEnd<sup>8+</sup> | Top right alignment. | | TopEnd<sup>8+</sup> | Top right alignment. |
...@@ -59,7 +59,7 @@ Opens the content of the custom dialog box. If the content has been displayed, t ...@@ -59,7 +59,7 @@ Opens the content of the custom dialog box. If the content has been displayed, t
### close ### close
close(): void close(): void
Closes the custom dialog box. If the dialog box is closed, the setting does not take effect. Closes the custom dialog box. If the dialog box is closed, this API does not take effect.
## Example ## Example
......
# Motion Path Animation # Motion Path Animation
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The attributes described in this topic are used to set the motion path of the component in a translation animation. The attributes below can be used to set the motion path of the component in a translation animation.
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| motionPath | {<br/>path: string,<br/>from?: number,<br/>to?: number,<br/>rotatable?: boolean<br/>}<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> In a path, **start** and **end** can be used to replace the start point and end point. Example:<br/>> <br/>> 'Mstart.x start.y L50 50 Lend.x end.y Z' | {<br/>"",<br/>0.0,<br/>1.0,<br/>false<br/>} | Motion path of the component. The input parameters are described as follows:<br/>- **path**: motion path of the translation animation. The **svg** path string is used.<br/>- **from**: start point of the motion path. The default value is **0.0**.<br/>- **to**: end point of the motion path. The default value is **1.0**.<br/>- **rotatable**: whether to rotate along the path. | | motionPath | {<br/>path: string,<br/>from?: number,<br/>to?: number,<br/>rotatable?: boolean<br/>}<br/>**NOTE**<br/>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br/>'Mstart.x start.y L50 50 Lend.x end.y Z' | {<br/>"",<br/>0.0,<br/>1.0,<br/>false<br/>} | Motion path of the component. The input parameters are described as follows:<br/>- **path**: motion path of the translation animation. The **svg** path string is used.<br/>- **from**: start point of the motion path. The default value is **0.0**.<br/>- **to**: end point of the motion path. The default value is **1.0**.<br/>- **rotatable**: whether to rotate along the path. |
## Example ## Example
......
...@@ -72,7 +72,7 @@ Declare the permissions required by the app one by one in the **config.json** fi ...@@ -72,7 +72,7 @@ Declare the permissions required by the app one by one in the **config.json** fi
The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL. The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL.
In addition to declaring all the permissions in the **config.json** file, you must declare the permissions whose levels are higher than the app's APL in the app's profile. In this example, declare the permission under the **acls** field: In addition to declaring all the permissions in the **config.json** file, you must declare the permissions whose levels are higher than the app's APL in the app's [profile](../quick-start/app-provision-structure.md). In this example, declare the permission under the **acls** field:
```json ```json
{ {
"version-name": "1.0.0", "version-name": "1.0.0",
......
...@@ -20,7 +20,7 @@ HUKS manages keys through the following operations: ...@@ -20,7 +20,7 @@ HUKS manages keys through the following operations:
- **Finish**: processes all data transferred to HUKS and then releases resources. - **Finish**: processes all data transferred to HUKS and then releases resources.
>![](../public_sys-resources/icon-notice.gif)**NOTICE**:<br/>If an error occurs in the **Init**, **Update**, or **Finish** operation, you must invoke the **Abort** operation to terminate the use of the key. >**NOTICE**<br/>The **Abort** operation is invoked to terminate the use of the key when an error occurs in the **Init**, **Update**, or **Finish** operation.
### Constraints ### Constraints
......
...@@ -29,26 +29,27 @@ In addition, OpenHarmony provides a wide array of system components that can be ...@@ -29,26 +29,27 @@ In addition, OpenHarmony provides a wide array of system components that can be
**Table 1** Mini and small system development guidelines (reference memory < 128 MiB) **Table 1** Mini and small system development guidelines (reference memory < 128 MiB)
| Topic| Development Scenario| Related Documentation| | Topic | Development Scenario | Related Documentation |
| -------- | -------- | -------- | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| About OpenHarmony| Getting familiar with OpenHarmony| -&nbsp;[About OpenHarmony](https://gitee.com/openharmony)<br>-&nbsp;[Glossary](../glossary.md) | | About OpenHarmony| Getting familiar with OpenHarmony | - [About OpenHarmony](https://gitee.com/openharmony)<br>- [Glossary](../glossary.md)|
| Development resources| Preparing for your development| -&nbsp;[Obtaining Source Code](get-code/sourcecode-acquire.md)<br>-&nbsp;[Obtaining Tools](get-code/gettools-acquire.md) | | Development resources | Preparing for your development | - [Obtaining Source Code](get-code/sourcecode-acquire.md)<br>- [Obtaining Tools](get-code/gettools-acquire.md) |
| Getting started| Getting started with setup, build, burning, debugging, and running of OpenHarmony| [Mini and Small Systems](quick-start/quickstart-ide-lite-overview.md)| | Getting started | Getting started with setup, build, burning, debugging, and running of OpenHarmony | - [Mini and Small System Overview](quick-start/quickstart-ide-lite-overview.md)|
| Basic capabilities| Using basic capabilities of OpenHarmony| -&nbsp;[Kernel for Mini System](kernel/kernel-mini-overview.md)<br>-&nbsp;[Kernel for Small System](kernel/kernel-small-overview.md)<br>-&nbsp;[HDF](driver/driver-hdf-overview.md)<br>-&nbsp;[Subsystems](subsystems/subsys-build-mini-lite.md)<br>-&nbsp;[Security Guidelines](security/security-guidelines-overall.md)<br>-&nbsp;[Privacy Protection](security/security-privacy-protection.md)| | Basic capabilities | Using basic capabilities of OpenHarmony | - [Kernel for Mini System](kernel/kernel-mini-overview.md)<br>- [Kernel for Small System](kernel/kernel-small-overview.md)<br>- [HDF](driver/driver-hdf-overview.md)<br>- [Subsystems](subsystems/subsys-build-mini-lite.md)<br>- [Security Guidelines](security/security-guidelines-overall.md)<br>- [Privacy Protection](security/security-privacy-protection.md)|
| Advanced development| Developing smart devices based on system capabilities| -&nbsp;[WLAN-connected Products](guide/device-wlan-led-control.md)<br>-&nbsp;[Cameras Without a Screen](guide/device-iotcamera-control-overview.md)<br>-&nbsp;[Cameras with a Screen](guide/device-camera-control-overview.md) | | Advanced development | Developing smart devices based on system capabilities | - [WLAN-connected Products](guide/device-wlan-led-control.md)<br>- [Cameras Without a Screen](guide/device-iotcamera-control-overview.md)<br>- [Cameras with a Screen](guide/device-camera-control-overview.md) |
| Porting and adaptation| -&nbsp;Porting and adapting OpenHarmony to an SoC<br>-&nbsp;Porting and adapting OpenHarmony to a third-party library| -&nbsp;[Mini System SoC Porting](porting/porting-minichip.md)<br>-&nbsp;[Small System SoC Porting](porting/porting-smallchip-prepare-needs.md)<br>-&nbsp;[Third-Party Library Porting for Mini and Small Systems](porting/porting-thirdparty-overview.md) | | Porting and adaptation | - Porting and adapting OpenHarmony to an SoC<br>- Porting and adapting OpenHarmony to a third-party library<br>- Third-party vendor porting cases<br>| - [Mini System SoC Porting Guide](porting/porting-minichip.md)<br>- [Small System SoC Porting Guide](porting/porting-smallchip-prepare-needs.md)<br>- [Third-Party Library Porting Guide for Mini and Small Systems](porting/porting-thirdparty-overview.md) <br> - [Mini-System Devices with Screens — Bestechnic SoC Porting Case](porting-bes2600w-on-minisystem-display-demo.md)<br> - [Combo Solution – ASR Chip Porting Case](porting/porting-asr582x-combo-demo.md)<br> |
| Contributing components| Contributing components to OpenHarmony| -&nbsp;[HPM Part Overview](hpm-part/hpm-part-about.md)<br>-&nbsp;[HPM Part Development](hpm-part/hpm-part-development.md)<br>-&nbsp;[HPM Part Reference](hpm-part/hpm-part-reference.md) | | Contributing components | Contributing components to OpenHarmony | - [HPM Part Overview](hpm-part/hpm-part-about.md)<br>- [HPM Part Development](hpm-part/hpm-part-development.md)<br>- [HPM Part Reference](hpm-part/hpm-part-reference.md) |
| Reference| Referring to development specifications| [FAQs](faqs/faqs-overview.md) | | Reference | Referring to development specifications | [FAQs](faqs/faqs-overview.md) |
**Table 2** Standard system development guidelines (reference memory ≥ 128 MiB) **Table 2** Standard system development guidelines (reference memory ≥ 128 MiB)
| Topic| Development Scenario| Related Documentation| | Topic| Development Scenario| Related Documentation|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| About OpenHarmony| Getting familiar with OpenHarmony| -&nbsp;[About OpenHarmony](https://gitee.com/openharmony)<br>-&nbsp;[Glossary](../glossary.md) | | About OpenHarmony| Getting familiar with OpenHarmony| - [About OpenHarmony](https://gitee.com/openharmony)<br>- [Glossary](../glossary.md)|
| Development resources| Preparing for your development| -&nbsp;[Obtaining Source Code](get-code/sourcecode-acquire.md)<br>-&nbsp;[Obtaining Tools](get-code/gettools-acquire.md) | | Development resources| Preparing for your development| - [Obtaining Source Code](get-code/sourcecode-acquire.md)<br>- [Obtaining Tools](get-code/gettools-acquire.md)|
| Getting started| Getting started with setup, build, burning, debugging, and running of OpenHarmony| [Standard System](quick-start/)| | Getting started| Getting started with setup, build, burning, debugging, and running of OpenHarmony| - [Standard System Overview](quick-start/quickstart-ide-standard-overview.md) |
| Basic capabilities| Using basic capabilities of OpenHarmony| -&nbsp;[Kernel Development](kernel/kernel-standard.md)<br>-&nbsp;[HDF](driver/driver-hdf-overview.md)<br>-&nbsp;[Subsystems](subsystems/subsys-build-standard-large.md)<br>-&nbsp;[Security Guidelines](security/security-guidelines-overall.md)<br>-&nbsp;[Privacy Protection](security/security-privacy-protection.md)| | Basic capabilities| Using basic capabilities of OpenHarmony| - [Kernel Development](kernel/kernel-standard.md)<br>- [HDF](driver/driver-hdf-overview.md)<br>- [Subsystems](subsystems/subsys-build-standard-large.md)<br>- [Security Guidelines](security/security-guidelines-overall.md)<br>- [Privacy Protection](security/security-privacy-protection.md)|
| Advanced development| Developing smart devices based on system capabilities| -&nbsp;[Development Guidelines on Clock Apps](guide/device-clock-guide.md)<br>-&nbsp;[Development Example for Platform Drivers](guide/device-driver-demo.md)<br>-&nbsp;[Development Example for Peripheral Drivers](guide/device-outerdriver-demo.md) | | Advanced development| Developing smart devices based on system capabilities| - [Development Guidelines on Clock Apps](guide/device-clock-guide.md)<br>- [Development Example for Platform Drivers](guide/device-driver-demo.md)<br>- [Development Example for Peripheral Drivers](guide/device-outerdriver-demo.md) |
| Porting and adaptation| Porting and adapting OpenHarmony to a third-party library| -&nbsp;[Standard System Porting Guide](porting/standard-system-porting-guide.md)<br>-&nbsp;[A Method for Rapidly Porting the OpenHarmony Linux Kernel](porting/porting-linux-kernel.md) | | Porting and adaptation| - Porting and adapting OpenHarmony to an SoC<br>- Rapidly porting the OpenHarmony Linux kernel| - [Standard System Porting Guide](porting/standard-system-porting-guide.md)<br>- [A Method for Rapidly Porting the OpenHarmony Linux Kernel](porting/porting-linux-kernel.md) |
| Contributing components| Contributing components to OpenHarmony| -&nbsp;[HPM Part Overview](hpm-part/hpm-part-about.md)<br>-&nbsp;[HPM Part Development](hpm-part/hpm-part-development.md)<br>-&nbsp;[HPM Part Reference](hpm-part/hpm-part-reference.md) | | Contributing components| Contributing components to OpenHarmony| - [HPM Part Overview](hpm-part/hpm-part-about.md)<br>- [HPM Part Development](hpm-part/hpm-part-development.md)<br>- [HPM Part Reference](hpm-part/hpm-part-reference.md) |
| Reference| Referring to development specifications| [FAQs](faqs/faqs-overview.md) | | Reference| Referring to development specifications| [FAQs](faqs/faqs-overview.md)|
...@@ -46,6 +46,7 @@ ...@@ -46,6 +46,7 @@
- [Audio](driver-peripherals-audio-des.md) - [Audio](driver-peripherals-audio-des.md)
- [Camera](driver-peripherals-camera-des.md) - [Camera](driver-peripherals-camera-des.md)
- [Facial Authentication](driver-peripherals-face_auth-des.md) - [Facial Authentication](driver-peripherals-face_auth-des.md)
- [Fingerprint Authentication](driver-peripherals-fingerprint_auth-des.md)
- [LCD](driver-peripherals-lcd-des.md) - [LCD](driver-peripherals-lcd-des.md)
- [Light](driver-peripherals-light-des.md) - [Light](driver-peripherals-light-des.md)
- [PIN Authentication](driver-peripherals-pinauth-des.md) - [PIN Authentication](driver-peripherals-pinauth-des.md)
......
# Fingerprint Authentication
## Overview
### Function
Fingerprint authentication is indispensable in identity authentication scenarios, such as device unlocking, payment, and app logins. The fingerprint authentication (Fingerprint_auth) module provides fingerprint authentication for a device after a user enrolls a fingerprint. The figure below shows the fingerprint authentication architecture.
The Fingerprint_auth driver is developed based on the Hardware Driver Foundation (HDF). It shields hardware differences and provides stable fingerprint authentication capabilities for the upper-layer user authentication (User_auth) framework and Fingerprint_auth service. It provides APIs for obtaining the fingerprint authentication executor list, executor information, and template information by template ID, comparing fingerprint template information of the executor and that of User_auth, enrolling or deleting fingerprints, and performing fingerprint authentication.
**Figure 1** Fingerprint authentication architecture
![image](figures/fingerprint_auth_architecture.png "Fingerprint authentication architecture")
### Basic Concepts
The identity authentication consists of the User_auth framework and basic authentication services. It supports basic functions such as setting and deleting user credentials and performing authentication. The system supports user identity authentication and data collection, processing, storage, and comparison.
- Executor
The executor collects, processes, stores, and compares data for authentication. Each authentication service provides the executor capabilities, which are scheduled by User_auth to implement basic capabilities.
- Executor security level
Security level required for the execution environment of an executor.
- Executor role
- Executor: independently completes the entire process of credential registration and identity authentication. The executor can collect, process, store, and compare data to complete the authentication.
- Collector: only collects data during user authentication. It needs to work with the authenticator to complete user authentication.
- Authenticator: only processes data, obtains the stored credential template, and compares it with the authentication information generated.
- Executor type
The authentication algorithm varies depending on the authentication mode and device used. Different executor types are defined based on the supported algorithm type or the device in use.
- User_auth public key & executor public key
To ensure user data security and authentication result accuracy, measures must be taken to protect the integrity of the key information exchanged between User_auth and basic authentication services. Public keys must be exchanged when the executor provided by a basic authentication service interworks with User_auth.
The executor uses the User_auth public key to verify scheduling instructions.
User_auth uses the executor public key to verify the authentication result accuracy and the integrity of the information exchanged with the executor.
- Authentication credential
Authentication credentials are generated and stored by the authentication service when users set authentication credentials. Each template has an ID to index a set of template information files. The template information needs to be compared with the authentication data generated during authentication to complete identity authentication.
- Data verification by the executor
User_auth manages the mappings between user identities and credential IDs in a unified manner. When connecting to User_auth, the executor obtains the template ID list from User_auth and updates its template ID list based on the template ID list obtained.
- HAPs
OpenHarmony Ability Packages (HAPs) represent the upper-layer applications of the Fingerprint_auth driver in this document.
- IDL interface
An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. In this document, the IDL interface implements communication between the Fingerprint_auth service and the driver.
- IPC
Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other.
### Working Principles
The fingerprint_auth driver provides stable basic fingerprint authentication capabilities for the upper-layer User_auth framework and Fingerprint_auth service to ensure successful fingerprint authentication on devices.
The figure below shows the interaction between the Fingerprint_auth service and the Fingerprint_auth driver.
The Fingerprint_auth service obtains the executor information by using **GetExecutorInfo()** and registers the executor with the User_auth framework. The Fingerprint_auth service exchanges information with the Fingerprint_auth driver for authentication, identification, and query through the executor APIs.
You can develop drivers to call Hardware Device Interface (HDI) APIs based on the HDF and the chip you use.
**Figure 2** Interaction between the Fingerprint_auth service and Fingerprint_auth driver
![image](figures/fingerprint_auth_service_and_driver_interaction.png "Fingerprint_auth service and driver interaction")
### Constraints
A Trusted Execution Environment (TEE) must be available on the device to store encrypted fingerprint feature information.
## Development Guidelines
### When to Use
The fingerprint_auth driver provides stable basic fingerprint authentication capabilities for the upper-layer User_auth framework and Fingerprint_auth service to ensure successful fingerprint authentication on devices. To implement the preceding functions, you need to develop the Fingerprint_auth driver based on the HDF, and then implement the APIs for obtaining the executor list and functional APIs such as authentication and query.
### Available APIs
**Table 1** Available APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. |
| GetExecutorInfo(ExecutorInfo& info) | Obtains the executor information, including the executor type, executor role, authentication type, security level, and executor public key.|
| GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about the template based on the specified ID. |
| OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.|
| Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls a fingerprint template. |
| Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Authenticates a fingerprint template. |
| Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Identifies a fingerprint template. |
| Delete(const std::vector<uint64_t>& templateIdList) | Deletes a fingerprint template. |
| Cancel(uint64_t scheduleId) | Cancels a fingerprint enrolling, authentication, or identification operation based on the **scheduleId**. |
| SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Sends commands to the Fingerprint_auth driver. |
**Table 2** Callbacks
| API | Description |
| ------------------------------------------------------------ | ------------------------ |
| 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.|
### How to Develop
The following uses the Hi3516D V300 development board as an example to demonstrate how to develop the Fingerprint_auth driver. <br/>The directory structure is as follows:
```undefined
// drivers/peripheral/fingerprint_auth
├── BUILD.gn # Build script
├── bundle.json # Module description file
└── hdi_service # Fingerprint_auth driver implementation
├── BUILD.gn # Build script
├── include # Header files
└── src
├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── fingerprint_auth_interface_driver.cpp # Fingerprint_auth driver entry
└── fingerprint_auth_interface_service.cpp # Implementation of the API for obtaining the executor list
```
The development procedure is as follows:
1. Develop the Fingerprint_auth driver based on the HDF using the **Bind()**, **Init()**, **Release()**, and **Dispatch()** functions. For details about the code, see [fingerprint_auth_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/fingerprint_auth_interface_driver.cpp).<br>The sample code is as follows:
```c++
// Create an IRemoteObject object by using the custom HdfFingerprintAuthInterfaceHost object, which consists of the IoService object and HDI service.
struct HdfFingerprintAuthInterfaceHost {
struct IDeviceIoService ioService;
OHOS::sptr<OHOS::IRemoteObject> stub;
};
// Enable the IPC service to call the response API.
static int32_t FingerprintAuthInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data,
struct HdfSBuf *reply)
{
IAM_LOGI("start");
auto *hdfFingerprintAuthInterfaceHost = CONTAINER_OF(client->device->service,
struct HdfFingerprintAuthInterfaceHost, ioService);
OHOS::MessageParcel *dataParcel = nullptr;
OHOS::MessageParcel *replyParcel = nullptr;
OHOS::MessageOption option;
if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) {
IAM_LOGE("%{public}s:invalid data sbuf object to dispatch", __func__);
return HDF_ERR_INVALID_PARAM;
}
if (SbufToParcel(reply, &replyParcel) != HDF_SUCCESS) {
IAM_LOGE("%{public}s:invalid reply sbuf object to dispatch", __func__);
return HDF_ERR_INVALID_PARAM;
}
return hdfFingerprintAuthInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option);
}
// Initialize the HdfFingerprintAuthInterfaceDriver object.
int HdfFingerprintAuthInterfaceDriverInit(struct HdfDeviceObject *deviceObject)
{
IAM_LOGI("start");
if (!HdfDeviceSetClass(deviceObject, DEVICE_CLASS_USERAUTH)) {
IAM_LOGE("set fingerprint auth hdf class failed");
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
// Bind the service provided by the Fingerprint_auth driver to the HDF.
int HdfFingerprintAuthInterfaceDriverBind(struct HdfDeviceObject *deviceObject)
{
IAM_LOGI("start");
auto *hdfFingerprintAuthInterfaceHost = new (std::nothrow) HdfFingerprintAuthInterfaceHost;
if (hdfFingerprintAuthInterfaceHost == nullptr) {
IAM_LOGE("%{public}s: failed to create HdfFaceAuthInterfaceHost object", __func__);
return HDF_FAILURE;
}
hdfFingerprintAuthInterfaceHost->ioService.Dispatch = FingerprintAuthInterfaceDriverDispatch;
hdfFingerprintAuthInterfaceHost->ioService.Open = NULL;
hdfFingerprintAuthInterfaceHost->ioService.Release = NULL;
auto serviceImpl = IFingerprintAuthInterface::Get(true);
if (serviceImpl == nullptr) {
IAM_LOGE("%{public}s: failed to implement service", __func__);
return HDF_FAILURE;
}
hdfFingerprintAuthInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl,
IFaceAuthInterface::GetDescriptor());
if (hdfFingerprintAuthInterfaceHost->stub == nullptr) {
IAM_LOGE("%{public}s: Failed to get stub object", __func__);
return HDF_FAILURE;
}
deviceObject->service = &hdfFingerprintAuthInterfaceHost->ioService;
IAM_LOGI("success");
return HDF_SUCCESS;
}
// Release the resources used by the Fingerprint_auth driver.
void HdfFingerprintAuthInterfaceDriverRelease(struct HdfDeviceObject *deviceObject)
{
IAM_LOGI("start");
auto *hdfFingerprintAuthInterfaceHost = CONTAINER_OF(deviceObject->service,
struct HdfFaceAuthInterfaceHost, ioService);
delete hdfFaceAuthInterfaceHost;
IAM_LOGI("success");
}
// Register the Fingerprint_auth driver entry data structure object.
struct HdfDriverEntry g_fingerprintAuthInterfaceDriverEntry = {
.moduleVersion = 1,
.moduleName = "fingerprint_auth_interface_service",
.Bind = HdfFingerprintAuthInterfaceDriverBind,
.Init = HdfFingerprintAuthInterfaceDriverInit,
.Release = HdfFingerprintAuthInterfaceDriverRelease,
};
// Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind() function and then the Init() function. If the Init() function fails to be called, the HDF will call Release() to release driver resources and exit the driver model.
HDF_INIT(g_fingerprintAuthInterfaceDriverEntry);
```
2. Implement the API for obtaining the executor list. For details about the code, see [fingerprint_auth_interface_service.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/fingerprint_auth_interface_service.cpp).<br>The sample code is as follows:
```c++
// Executor implementation class
class ExecutorImpl : public IExecutor {
public:
ExecutorImpl(struct ExecutorInfo executorInfo);
virtual ~ExecutorImpl() {}
private:
struct ExecutorInfo executorInfo_; // Executor information
};
static constexpr uint16_t SENSOR_ID = 123; // Executor sensor ID
static constexpr uint32_t EXECUTOR_TYPE = 123; // Executor type
static constexpr size_t PUBLIC_KEY_LEN = 32; //32-byte public key of the executor
// Create an HDI service object.
extern "C" IFaceAuthInterface *FingerprintAuthInterfaceImplGetInstance(void)
{
auto fingerprintAuthInterfaceService = new (std::nothrow) FingerprintAuthInterfaceService();
if (fingerprintAuthInterfaceService == nullptr) {
IAM_LOGE("faceAuthInterfaceService is nullptr");
return nullptr;
}
return fingerprintAuthInterfaceService;
}
// Obtain the executor list and create an executor.
int32_t GetExecutorList(std::vector<sptr<IExecutor>>& executorList)
{
IAM_LOGI("interface mock start");
executorList.clear();
struct ExecutorInfo executorInfoExample = {
.sensorId = SENSOR_ID,
.executorType = EXECUTOR_TYPE,
.executorRole = ExecutorRole::ALL_IN_ONE,
.authType = AuthType::FINGERPRINT,
.esl = ExecutorSecureLevel::ESL0, // Executor security level, which ranges from ESL0 to ESL3 (highest).
.publicKey = std::vector<uint8_t>(PUBLIC_KEY_LEN, 0), // 32-byte public key, using the Ed25519 algorithm.
.extraInfo = {},
};
auto executor = new (std::nothrow) ExecutorImpl(executorInfoExample);
if (executor == nullptr) {
IAM_LOGE("executor is nullptr");
return HDF_FAILURE;
}
executorList.push_back(sptr<IExecutor>(executor));
IAM_LOGI("interface mock success");
return HDF_SUCCESS;
}
```
3. Implement each function of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/executor_impl.cpp).<br>The sample code is as follows:
```c++
// Obtain the executor information.
int32_t GetExecutorInfo(ExecutorInfo& info)
{
IAM_LOGI("interface mock start");
info = executorInfo_;
IAM_LOGI("Executor information got successfully");
return HDF_SUCCESS;
}
// Obtain template information based on templateId.
int32_t GetTemplateInfo(uint64_t templateId, TemplateInfo& info)
{
IAM_LOGI("interface mock start");
static_cast<void>(templateId);
info = {0};
IAM_LOGI("Template information got successfully");
return HDF_SUCCESS;
}
// After the executor is successfully registered, obtain the public key and template ID list from User_auth and save the public key. The executor compares its template ID list with the template ID list obtained and updates its template ID list.
int32_t OnRegisterFinish(const std::vector<uint64_t>& templateIdList,
const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo)
{
IAM_LOGI("interface mock start");
static_cast<void>(templateIdList);
static_cast<void>(extraInfo);
static_cast<void>(frameworkPublicKey);
IAM_LOGI("registration finished");
return HDF_SUCCESS;
}
// Enroll fingerprints.
int32_t Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,
const sptr<IExecutorCallback>& callbackObj)
{
IAM_LOGI("interface mock start");
static_cast<void>(scheduleId);
static_cast<void>(extraInfo);
IAM_LOGI("enroll, result is %{public}d", ResultCode::OPERATION_NOT_SUPPORT);
int32_t ret = callbackObj->OnResult(ResultCode::OPERATION_NOT_SUPPORT, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
// Authenticate fingerprints.
int32_t Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,
const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj)
{
IAM_LOGI("interface mock start");
static_cast<void>(scheduleId);
static_cast<void>(templateIdList);
static_cast<void>(extraInfo);
IAM_LOGI("authenticate, result is %{public}d", ResultCode::NOT_ENROLLED);
int32_t ret = callbackObj->OnResult(ResultCode::NOT_ENROLLED, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
// Identify fingerprints.
int32_t Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,
const sptr<IExecutorCallback>& callbackObj)
{
IAM_LOGI("interface mock start");
static_cast<void>(scheduleId);
static_cast<void>(extraInfo);
IAM_LOGI("identify, result is %{public}d", ResultCode::OPERATION_NOT_SUPPORT);
int32_t ret = callbackObj->OnResult(ResultCode::OPERATION_NOT_SUPPORT, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
// Delete a fingerprint template.
int32_t Delete(const std::vector<uint64_t>& templateIdList)
{
IAM_LOGI("interface mock start");
static_cast<void>(templateIdList);
IAM_LOGI("delete success");
return HDF_SUCCESS;
}
// Cancel the operation based on the specified scheduleId.
int32_t Cancel(uint64_t scheduleId)
{
IAM_LOGI("interface mock start");
static_cast<void>(scheduleId);
IAM_LOGI("cancel success");
return HDF_SUCCESS;
}
// Send template locking or unlocking command from the Fingerprint_auth service to the Fingerprint_auth driver.
int32_t SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,
const sptr<IExecutorCallback>& callbackObj)
{
IAM_LOGI("interface mock start");
static_cast<void>(extraInfo);
int32_t ret;
switch (commandId) {
case LOCK_TEMPLATE:
IAM_LOGI("unlock template, result is %{public}d", ResultCode::SUCCESS);
ret = callbackObj->OnResult(ResultCode::SUCCESS, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
break;
case UNLOCK_TEMPLATE:
IAM_LOGI("unlock template, result is %{public}d", ResultCode::SUCCESS);
ret = callbackObj->OnResult(ResultCode::SUCCESS, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
break;
default:
IAM_LOGD("not support CommandId : %{public}d", commandId);
ret = callbackObj->OnResult(ResultCode::GENERAL_ERROR, {});
if (ret != ResultCode::SUCCESS) {
IAM_LOGE("callback result is %{public}d", ret);
return HDF_FAILURE;
}
}
return HDF_SUCCESS;
}
```
4. Modify **serviceName2Config** in the **fingerprint_auth_service.cpp** file if you need to add a driver or modify driver information.
```c++
// base/user_iam/fingerprint_auth/services/src/fingerprint_auth_service.cpp
void FingerprintAuthService::StartDriverManager()
{
IAM_LOGI("start");
// Service name and ID of the driver to add or modify. The driver service name and ID must be globally unique.
const std::map<std::string, UserAuth::ServiceConfig> serviceName2Config = {
{"fingerprint_auth_interface_service", {2, std::make_shared<FingerprintAuthDriverHdi>()}},
};
UserIAM::UserAuth::IDriverManager::GetInstance().Start(serviceName2Config);
}
```
### Verification
Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The JavaScript application invokes the Fingerprint_auth driver via the Fingerprint_auth service.
The sample code is as follows:
```js
// API version 8
import userIAM_userAuth from '@ohos.userIAM.userAuth';
let auth = new userIAM_userAuth.UserAuth();
export default {
getVersion() {
console.info("start to get version");
let version = this.auth.getVersion();
console.info("auth version = " + version);
},
startAuth() {
console.info("start auth");
// auth is an API that can be called. You can set the authentication type to FINGERPRINT to check whether the driver is successfully registered with the framework and whether the authentication APIs are implemented as expected. result holds the authentication result.
this.auth.auth(null, userIAM_userAuth.UserAuthType.FINGERPRINT, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
try {
console.info("auth onResult result = " + result);
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
if (result == userIAM_userAuth.ResultCode.SUCCESS) {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (e) {
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
try {
console.info("auth onAcquireInfo module = " + module);
console.info("auth onAcquireInfo acquire = " + acquire);
console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
} catch (e) {
console.info("auth onAcquireInfo error = " + e);
}
}
});
}
}
```
...@@ -5,7 +5,9 @@ ...@@ -5,7 +5,9 @@
### Light ### Light
The light driver model provides APIs for the upper-layer light hardware service layer to control lights, including obtaining the light type, setting the lighting mode and blinking effect, and turning on or off a light. This model implements functionalities such as cross-OS migration and differentiated configurations based on the Hardware Driver Foundation (HDF) to achieve the goal of "one-time development for cross-system deployment" of the light driver. The figure below shows the light driver model. The light driver model provides APIs for the upper-layer light hardware service layer to control lights, including obtaining the light type, setting the lighting mode and blinking effect, and turning on or off a light. This model implements functionalities such as cross-OS migration and differentiated configurations based on the Hardware Driver Foundation (HDF) to achieve the goal of "one-time development for cross-system deployment" of the light driver.
The figure below shows the light driver model.
**Figure 1** Light driver model **Figure 1** Light driver model
...@@ -23,7 +25,7 @@ The following uses the Hi3516D V300 development board powered by the standard sy ...@@ -23,7 +25,7 @@ The following uses the Hi3516D V300 development board powered by the standard sy
1. The light driver reads the light device management configuration from **Light Host** in the **device_info.hcs** file. 1. The light driver reads the light device management configuration from **Light Host** in the **device_info.hcs** file.
2. The light driver reads the light data configuration from the **light_config.hcs** file. 2. The light driver reads the light data configuration from the **light_config.hcs** file.
3. The light driver parses information about the light device management configuration and associates with the corresponding device driver. 3. The light driver parses the light device management configuration and associates with the corresponding device driver.
4. The light proxy delivers an instruction to the light stub. 4. The light proxy delivers an instruction to the light stub.
5. The light stub delivers an instruction to the light controller. 5. The light stub delivers an instruction to the light controller.
6. The light abstract driver interface is started. 6. The light abstract driver interface is started.
...@@ -42,15 +44,15 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -42,15 +44,15 @@ The light driver model provides APIs to obtain information about all the lights
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| int32_t (*GetLightInfo)(struct LightInfo **lightInfo, uint32_t *count) | Obtains information about all lights in the system. **lightInfo** indicates the double pointer to the basic light information. **count** indicates the pointer to the number of lights.| | int32_t (*GetLightInfo)(struct LightInfo **lightInfo, uint32_t *count) | Obtains information about all lights in the system. <br/>-&nbsp;**lightInfo** indicates the double pointer to the basic light information. <br/>-&nbsp;**count** indicates the pointer to the number of lights. |
| int32_t (*TurnOnLight)(uint32_t type, struct LightEffect *effect) | Turns on available lights in the list based on the specified light type. **type** indicates the light type, and **effect** indicates the pointer to the blinking effect.| | int32_t (*TurnOnLight)(uint32_t lightId, struct LightEffect *effect) | Turns on available lights in the list based on the specified light type. <br/>**lightId** indicates the light type, and **effect** indicates the pointer to the blinking effect. |
| int32_t (*TurnOffLight)(uint32_t type) | Turns off available lights in the light list based on the specified light type. **type** indicates the light type. | | int32_t (*TurnOffLight)(uint32_t lightId) | Turns off available lights in the light list based on the specified light type. <br/>**lightId** indicates the light type. |
### How to Develop ### How to Develop
1. Based on the HDF and the driver entry, complete the light abstract driver development (using the **Bind**, **Init**, **Release**, and **Dispatch** functions), resource configuration, and HCS parsing. Configure the light driver device information. 1. Based on the HDF and the driver entry, complete the light abstract driver development (using the **Bind**, **Init**, **Release**, and **Dispatch** functions), resource configuration, and HCS parsing. Configure the light driver device information.
- Call **HDF_INIT** to register the driver entry with the HDF. Generally, the HDF calls the **Bind** function and then the **Init** function to load the driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit. - Call **HDF_INIT** to register the driver entry with the HDF. Generally, the HDF calls the **Bind** function and then the **Init** function to load the driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
The light driver model uses HDF configuration source (HCS). For details about HCS fields, see [Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md). The light driver model uses HDF configuration source (HCS). For details about HCS fields, see [Configuration Management](../driver/driver-hdf-manage.md).
The light driver entry is defined as follows: The light driver entry is defined as follows:
```c ```c
...@@ -62,7 +64,7 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -62,7 +64,7 @@ The light driver model provides APIs to obtain information about all the lights
.Init = InitLightDriver, // Initialize the light driver. .Init = InitLightDriver, // Initialize the light driver.
.Release = ReleaseLightDriver, // Release the light resources. .Release = ReleaseLightDriver, // Release the light resources.
}; };
/* Call HDF_INIT to register the driver entry with the HDF. The HDF calls the Bind function and then the Init function to load a driver. If Init fails to be called, the HDF calls Release to release driver resources and exit. */ /* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls Bind() and then Init() to load the driver. If Init() fails to be called, the HDF will call Release() to release resources and exit. */
HDF_INIT(g_lightDriverEntry); HDF_INIT(g_lightDriverEntry);
``` ```
...@@ -81,13 +83,13 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -81,13 +83,13 @@ The light driver model provides APIs to obtain information about all the lights
CHECK_LIGHT_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM); CHECK_LIGHT_NULL_PTR_RETURN_VALUE(data, HDF_ERR_INVALID_PARAM);
(void)OsalMutexLock(&drvData->mutex); (void)OsalMutexLock(&drvData->mutex);
if (!HdfSbufReadInt32(data, &lightType)) { if (!HdfSbufReadInt32(data, &lightId)) {
HDF_LOGE("%s: sbuf read lightType failed", __func__); HDF_LOGE("%s: sbuf read lightId fail", __func__);
(void)OsalMutexUnlock(&drvData->mutex); (void)OsalMutexUnlock(&drvData->mutex);
return HDF_ERR_INVALID_PARAM; return HDF_ERR_INVALID_PARAM;
} }
..... .....
ret = DispatchCmdHandle(lightType, data, reply); ret = DispatchCmdHandle(lightId, data, reply);
(void)OsalMutexUnlock(&drvData->mutex); (void)OsalMutexUnlock(&drvData->mutex);
return ret; return ret;
} }
...@@ -128,6 +130,11 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -128,6 +130,11 @@ The light driver model provides APIs to obtain information about all the lights
HDF_LOGE("%s: get light config fail!", __func__); HDF_LOGE("%s: get light config fail!", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
/* Set the GPIO pin direction. */
if (SetLightGpioDir(drvData) != HDF_SUCCESS) {
HDF_LOGE("%s: set light gpio dir fail!", __func__);
return HDF_FAILURE;
}
return HDF_SUCCESS; return HDF_SUCCESS;
} }
...@@ -153,18 +160,18 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -153,18 +160,18 @@ The light driver model provides APIs to obtain information about all the lights
} }
``` ```
- The light device management module dispatches light device APIs in the system. During the system startup process, the HDF loads the device management driver from the HCS of the light host. - The light device management module publishes light device APIs in the system. During the system startup process, the HDF loads the device management driver based on **Light Host** in the HCS.
``` ```
/* Light device HCS */ /* Light device HCS */
device_light :: device { device_light :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 2; // Driver service dispatch policy (0: no service is dispatched; 1: services are dispatched to the kernel mode; 2: services are dispatched to both the kernel mode and user mode) policy = 2; // Policy for the driver to publish services. (0: The driver does not provide services. 1: The driver publishes services for the kernel space. 2: The driver publishes services for both the kernel space and user space.)
priority = 100; // Light driver startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The value 100 is recommended. If the priorities are the same, the device loading sequence cannot be ensured. priority = 100; // Light driver startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The value 100 is recommended. If the priorities are the same, the device loading sequence cannot be ensured.
preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. preload = 0; // Whether to load the driver on demand. The value 0 means to load the driver on demand; the value 2 means the opposite.
permission = 0664; // Permission for the driver to create a device node. permission = 0664; // Permission for the driver to create a device node.
moduleName = "HDF_LIGHT"; // Light driver name. The value of this field must be the same as that of moduleName in the HdfDriverEntry structure. moduleName = "HDF_LIGHT"; // Light driver name. The value of this field must be the same as that of moduleName in the HdfDriverEntry structure.
serviceName = "hdf_light"; // Service name of the driver, which must be unique. serviceName = "hdf_light"; // Unique name of the service published by the driver.
deviceMatchAttr = "hdf_light_driver"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. deviceMatchAttr = "hdf_light_driver"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
} }
``` ```
...@@ -173,16 +180,16 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -173,16 +180,16 @@ The light driver model provides APIs to obtain information about all the lights
```c ```c
/* Allocate resources and parse the HCS. */ /* Allocate resources and parse the HCS. */
static int32_t ParseLightInfo(const struct DeviceResourceNode *node) static int32_t ParseLightInfo(const struct DeviceResourceNode *node, const struct DeviceResourceIface *parser)
{ {
..... .....
/* Obtain the number of supported light types from the HCS. */ /* Obtain the number of supported light types from the HCS. */
drvData->lightNum = parser->GetElemNum(light, "lightType"); drvData->lightNum = parser->GetElemNum(light, "lightId");
.... ....
for (i = 0; i < drvData->lightNum; ++i) { for (i = 0; i < drvData->lightNum; ++i) {
/* Obtains the light type information. */ /* Obtain the light type. */
ret = parser->GetUint32ArrayElem(light, "lightType", i, &temp, 0); ret = parser->GetUint32ArrayElem(light, "lightId", i, &temp, 0);
CHECK_LIGHT_PARSER_RESULT_RETURN_VALUE(ret, "lightType"); CHECK_LIGHT_PARSER_RESULT_RETURN_VALUE(ret, "lightId");
} }
for (i = 0; i < drvData->lightNum; ++i) { for (i = 0; i < drvData->lightNum; ++i) {
...@@ -191,12 +198,19 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -191,12 +198,19 @@ The light driver model provides APIs to obtain information about all the lights
drvData->info[temp] = (struct LightDeviceInfo *)OsalMemCalloc(sizeof(struct LightDeviceInfo)); drvData->info[temp] = (struct LightDeviceInfo *)OsalMemCalloc(sizeof(struct LightDeviceInfo));
..... .....
/* Fill in the light device information. */ /* Fill in the light device information. */
ret = parser->GetUint32(light, "busRNum", &drvData->info[temp]->busRNum, 0); ret = parser->GetUint32(node, "busRNum", (uint32_t *)&drvData->info[temp]->busRNum, 0);
CHECK_LIGHT_PARSER_RESULT_RETURN_VALUE(ret, "busRNum"); if (ret != HDF_SUCCESS) {
ret = parser->GetUint32(light, "busGNum", &drvData->info[temp]->busGNum, 0); /* If busNum fails to be obtained, the color of the light corresponding to busNum cannot be set. */
CHECK_LIGHT_PARSER_RESULT_RETURN_VALUE(ret, "busGNum"); drvData->info[temp]->busRNum = LIGHT_INVALID_GPIO;
ret = parser->GetUint32(light, "busBNum", &drvData->info[temp]->busBNum, 0); }
CHECK_LIGHT_PARSER_RESULT_RETURN_VALUE(ret, "busBNum"); ret = parser->GetUint32(node, "busGNum", (uint32_t *)&drvData->info[temp]->busGNum, 0);
if (ret != HDF_SUCCESS) {
drvData->info[temp]->busGNum = LIGHT_INVALID_GPIO;
}
ret = parser->GetUint32(node, "busBNum", (uint32_t *)&drvData->info[temp]->busBNum, 0);
if (ret != HDF_SUCCESS) {
drvData->info[temp]->busBNum = LIGHT_INVALID_GPIO;
}
..... .....
return HDF_SUCCESS; return HDF_SUCCESS;
} }
...@@ -205,25 +219,25 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -205,25 +219,25 @@ The light driver model provides APIs to obtain information about all the lights
3. Call related APIs to obtain the light type, turn on and off lights, and create and delete the timer based on the blinking mode. 3. Call related APIs to obtain the light type, turn on and off lights, and create and delete the timer based on the blinking mode.
```c ```c
/* Call GetAllLightInfo to obtain the light type. Call Enable to enable the blinking mode. /* Call GetAllLightInfo() to obtain the light type. Call TurnOnLight() to enable the blinking mode.
Call Disable to stop blinking. */ Call TurnOffLight() to stop blinking. */
static int32_t GetAllLightInfo(struct HdfSBuf *data, struct HdfSBuf *reply) static int32_t GetAllLightInfo(struct HdfSBuf *data, struct HdfSBuf *reply)
{ {
..... .....
/* Obtain the number of light types. */ /* Obtain the number of light types. */
if (!HdfSbufWriteUint32(reply, drvData->lightNum)) { if (!HdfSbufWriteUint32(reply, drvData->lightNum)) {
HDF_LOGE("%s: write sbuf failed", __func__); HDF_LOGE("%s: write sbuf fail", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
for (i = 0; i < LIGHT_TYPE_BUTT; ++i) { for (i = 0; i < LIGHT_TYPE_BUTT; ++i) {
if (drvData->info[i] == NULL) { if (drvData->info[i] == NULL) {
continue; continue;
} }
lightInfo.lightType = i; lightInfo.lightId = i;
lightInfo.reserved = NULL; lightInfo.reserved = NULL;
/* Fill the light device information into the reply. */ /* Fill the light device information into the reply. */
if (!HdfSbufWriteBuffer(reply, &lightInfo, sizeof(lightInfo))) { if (!HdfSbufWriteBuffer(reply, &lightInfo, sizeof(lightInfo))) {
HDF_LOGE("%s: write sbuf failed", __func__); HDF_LOGE("%s: write sbuf fail", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
} }
...@@ -231,36 +245,65 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -231,36 +245,65 @@ The light driver model provides APIs to obtain information about all the lights
return HDF_SUCCESS; return HDF_SUCCESS;
} }
/* Enable lights based on the specified light type and input parameters. */ /* Update the status of the lights of the specified type. */
static int32_t Enable(uint32_t lightType, struct HdfSBuf *data, struct HdfSBuf *reply) static int32_t UpdateLight(uint32_t lightId, uint32_t lightOn)
{ {
..... .....
/* Set the light color based on the brightness value passed in. Red: bits 16–31; Green: bits 8–15; Blue: bits 0–7 */ /* If the lightBrightness value passed in is invalid, use the default value. */
if ((drvData->info[lightType]->lightBrightness & LIGHT_MAKE_R_BIT) != 0) { if (drvData->info[lightId]->lightBrightness == 0) {
drvData->info[lightType]->busNum = drvData->info[lightType]->busRNum; lightBrightness = drvData->info[lightId]->defaultBrightness;
} else if ((drvData->info[lightType]->lightBrightness & LIGHT_MAKE_G_BIT) != 0) { } else {
drvData->info[lightType]->busNum = drvData->info[lightType]->busGNum; lightBrightness = drvData->info[lightId]->lightBrightness;
} else if ((drvData->info[lightType]->lightBrightness & LIGHT_MAKE_B_BIT) != 0) { }
drvData->info[lightType]->busNum = drvData->info[lightType]->busBNum; /* If bits 0 to 7 are not 0, output the GPIO pin corresponding to blue based on the status of lightOn. */
if ((lightBrightness & LIGHT_MAKE_B_BIT) != 0) {
ret = WriteGpio(drvData->info[lightId]->busBNum, lightOn);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: write blue gpio fail", __func__);
return HDF_FAILURE;
} }
/* The light is steady on. */ }
if (buf->flashEffect.flashMode == LIGHT_FLASH_NONE) { /* If bits 8 to 15 are not 0, output the GPIO pin corresponding to green based on the status of lightOn. */
if ((lightBrightness & LIGHT_MAKE_G_BIT) != 0) {
if (GpioWrite(drvData->info[lightType]->busNum, GPIO_VAL_HIGH) != HDF_SUCCESS) { ret = WriteGpio(drvData->info[lightId]->busGNum, lightOn);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: write green gpio fail", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
} }
/* If bits 16 to 23 are not 0, output the GPIO pin corresponding to red based on the status of lightOn. */
if ((lightBrightness & LIGHT_MAKE_R_BIT) != 0) {
ret = WriteGpio(drvData->info[lightId]->busRNum, lightOn);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: write red gpio fail", __func__);
return HDF_FAILURE;
}
}
.....
}
/* Enable lights based on the specified light type and input parameters. */
static int32_t TurnOnLight(uint32_t lightId, struct HdfSBuf *data, struct HdfSBuf *reply)
{
.....
/* Receive the lightBrightness value passed in. Bits 24 to 31 are extension bits, bits 16 to 23 indicate red, bits 8 to 15 indicate green, and bits 0 to 7 indicate blue. If lightBrightness is not 0, enable the light in the specified color.
Set the light brightness to a value ranging from 0 to 255 if supported. */
drvData->info[lightId]->lightBrightness = buf->lightBrightness;
/* The light is steady on. */
if (buf->flashEffect.flashMode == LIGHT_FLASH_NONE) {
return UpdateLight(lightId, LIGHT_STATE_START);
}
/* The light is blinking. */ /* The light is blinking. */
if (buf->flashEffect.flashMode == LIGHT_FLASH_TIMED) { if (buf->flashEffect.flashMode == LIGHT_FLASH_TIMED) {
drvData->info[lightType]->lightState = LIGHT_STATE_START; drvData->info[lightId]->lightState = LIGHT_STATE_START;
/* If the specified blinking duration is less than the minimum time period supported by the system, the time configured by the system (in HCS) is used. */ /* If the specified blinking duration is less than the minimum time period supported by the system, the time configured by the system (in HCS) is used. */
drvData->info[lightType]->onTime = buf->flashEffect.onTime < drvData->info[lightType]->onTime ? drvData->info[lightId]->onTime = buf->flashEffect.onTime < drvData->info[lightId]->onTime ?
drvData->info[lightType]->onTime : buf->flashEffect.onTime; drvData->info[lightId]->onTime : buf->flashEffect.onTime;
drvData->info[lightType]->offTime = buf->flashEffect.offTime < drvData->info[lightType]->offTime ? drvData->info[lightId]->offTime = buf->flashEffect.offTime < drvData->info[lightId]->offTime ?
drvData->info[lightType]->offTime : buf->flashEffect.offTime; drvData->info[lightId]->offTime : buf->flashEffect.offTime;
/* Create a timer. */ /* Create a timer. */
if (OsalTimerCreate(&drvData->timer, drvData->info[lightType]->onTime, if (OsalTimerCreate(&drvData->timer, drvData->info[lightId]->onTime,
LightTimerEntry, (uintptr_t)lightType) != HDF_SUCCESS) { LightTimerEntry, (uintptr_t)lightId) != HDF_SUCCESS) {
HDF_LOGE("%s: create light timer fail!", __func__); HDF_LOGE("%s: create light timer fail!", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
...@@ -274,7 +317,7 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -274,7 +317,7 @@ The light driver model provides APIs to obtain information about all the lights
} }
/* Turn off lights based on the specified light type. */ /* Turn off lights based on the specified light type. */
static int32_t Disable(uint32_t lightType, struct HdfSBuf *data, struct HdfSBuf *reply) static int32_t TurnOffLight(uint32_t lightId, struct HdfSBuf *data, struct HdfSBuf *reply)
{ {
/* Delete the timer. */ /* Delete the timer. */
if (drvData->timer.realTimer != NULL) { if (drvData->timer.realTimer != NULL) {
...@@ -283,9 +326,8 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -283,9 +326,8 @@ The light driver model provides APIs to obtain information about all the lights
HDF_LOGE("%s: delete haptic timer fail!", __func__); HDF_LOGE("%s: delete haptic timer fail!", __func__);
} }
} }
/* Power off the corresponding GPIO. */ if (UpdateLight(lightId, LIGHT_STATE_STOP) != HDF_SUCCESS) {
if (GpioWrite(drvData->info[lightType]->busRNum, GPIO_VAL_LOW) != HDF_SUCCESS){ HDF_LOGE("%s: gpio write fail", __func__);
HDF_LOGE("%s: gpio write failed", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
...@@ -298,16 +340,16 @@ The light driver model provides APIs to obtain information about all the lights ...@@ -298,16 +340,16 @@ The light driver model provides APIs to obtain information about all the lights
After the driver is developed, develop auto-test cases in the light unit test to verify the basic functionalities of the driver. Use the developer self-test platform as the test environment. After the driver is developed, develop auto-test cases in the light unit test to verify the basic functionalities of the driver. Use the developer self-test platform as the test environment.
```c++ ```c++
/* Initialize the light interface instance before executing the test case. */ /* Initialize the LightInterfaceInstance before executing the test case. */
void HdfLightTest::SetUpTestCase() void HdfLightTest::SetUpTestCase()
{ {
g_lightDev = NewLightInterfaceInstance(); g_lightDev = NewLightInterfaceInstance();
if (g_lightDev == nullptr) { if (g_lightDev == nullptr) {
printf("test light get Module instance failed\n\r"); printf("test light get Module instance fail\n\r");
} }
int32_t ret = g_lightDev->GetLightInfo(&g_lightInfo, &g_count); int32_t ret = g_lightDev->GetLightInfo(&g_lightInfo, &g_count);
if (ret == -1) { if (ret == -1) {
printf("get light informations failed\n\r"); printf("get light informations fail\n\r");
} }
} }
...@@ -334,9 +376,9 @@ HWTEST_F(HdfLightTest, GetLightList001, TestSize.Level1) ...@@ -334,9 +376,9 @@ HWTEST_F(HdfLightTest, GetLightList001, TestSize.Level1)
info = g_lightInfo; info = g_lightInfo;
for (int i = 0; i < g_count; ++i) { for (int i = 0; i < g_count; ++i) {
printf("get lightId[%d]\n\r", info->lightType); printf("get lightId[%d]\n\r", info->lightId);
EXPECT_GE(info->lightType, g_minLightType); EXPECT_GE(info->lightId, g_minLightId);
EXPECT_LE(info->lightType, g_maxLightType); EXPECT_LE(info->lightId, g_maxLightId);
info++; info++;
} }
} }
...@@ -347,14 +389,14 @@ HWTEST_F(HdfLightTest, EnableLight001, TestSize.Level1) ...@@ -347,14 +389,14 @@ HWTEST_F(HdfLightTest, EnableLight001, TestSize.Level1)
int32_t i; int32_t i;
int32_t ret; int32_t ret;
struct LightEffect effect; struct LightEffect effect;
effect->lightBrightness = 0x80000000; effect->lightBrightness = 0x00800000;
effect->flashEffect.flashMode = LIGHT_FLASH_NONE; effect->flashEffect.flashMode = LIGHT_FLASH_NONE;
effect->flashEffect.onTime = 0; effect->flashEffect.onTime = 0;
effect->flashEffect.offTime = 0; effect->flashEffect.offTime = 0;
for (i = 0; i < g_count; ++i) { for (i = 0; i < g_count; ++i) {
ret = g_lightDev->TurnOnLight(g_lightInfo[i]->lightType, effect); ret = g_lightDev->TurnOnLight(g_lightInfo[i]->lightId, effect);
EXPECT_EQ(0, ret); EXPECT_EQ(0, ret);
OsalSleep(LIGHT_WAIT_TIME); OsalSleep(LIGHT_WAIT_TIME);
...@@ -370,14 +412,14 @@ HWTEST_F(HdfLightTest, EnableLight002, TestSize.Level1) ...@@ -370,14 +412,14 @@ HWTEST_F(HdfLightTest, EnableLight002, TestSize.Level1)
int32_t i; int32_t i;
int32_t ret; int32_t ret;
struct LightEffect effect; struct LightEffect effect;
effect->lightBrightness = 0x80000000; effect->lightBrightness = 0x00800000;
effect->flashEffect.flashMode = LIGHT_FLASH_TIMED; effect->flashEffect.flashMode = LIGHT_FLASH_TIMED;
effect->flashEffect.onTime = g_onTime; effect->flashEffect.onTime = g_onTime;
effect->flashEffect.offTime = g_offTime; effect->flashEffect.offTime = g_offTime;
for (i = 0; i < g_count; ++i) { for (i = 0; i < g_count; ++i) {
ret = g_lightDev->TurnOnLight(g_lightInfo[i]->lightType, effect); ret = g_lightDev->TurnOnLight(g_lightInfo[i]->lightId, effect);
EXPECT_EQ(0, ret); EXPECT_EQ(0, ret);
OsalSleep(LIGHT_WAIT_TIME); OsalSleep(LIGHT_WAIT_TIME);
......
...@@ -187,7 +187,7 @@ The development procedure is as follows: ...@@ -187,7 +187,7 @@ The development procedure is as follows:
auto *hdfUserAuthInterfaceHost = new (std::nothrow) HdfUserAuthInterfaceHost; auto *hdfUserAuthInterfaceHost = new (std::nothrow) HdfUserAuthInterfaceHost;
if (hdfUserAuthInterfaceHost == nullptr) { if (hdfUserAuthInterfaceHost == nullptr) {
HDF_LOGE("%{public}s: failed to create create HdfUserAuthInterfaceHost object", __func__); HDF_LOGE("%{public}s: Failed to create HdfUserAuthInterfaceHost object", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
...@@ -271,7 +271,7 @@ The development procedure is as follows: ...@@ -271,7 +271,7 @@ The development procedure is as follows:
int32_t ret = OpenEditSession(userId, &challengeU64); int32_t ret = OpenEditSession(userId, &challengeU64);
challenge.resize(sizeof(uint64_t)); challenge.resize(sizeof(uint64_t));
if (memcpy_s(&challenge[0], challenge.size(), &challengeU64, sizeof(uint64_t)) != EOK) { if (memcpy_s(&challenge[0], challenge.size(), &challengeU64, sizeof(uint64_t)) != EOK) {
IAM_LOGE("challengeU64 copy failed"); IAM_LOGE("Failed to copy challengeU64");
return RESULT_BAD_COPY; return RESULT_BAD_COPY;
} }
GlobalUnLock(); GlobalUnLock();
...@@ -310,7 +310,7 @@ The development procedure is as follows: ...@@ -310,7 +310,7 @@ The development procedure is as follows:
CoAuthSchedule scheduleInfo; CoAuthSchedule scheduleInfo;
int32_t ret = CheckEnrollPermission(checkParam, &scheduleInfo.scheduleId); int32_t ret = CheckEnrollPermission(checkParam, &scheduleInfo.scheduleId);
if (ret != RESULT_SUCCESS) { if (ret != RESULT_SUCCESS) {
IAM_LOGE("Permission check failed"); IAM_LOGE("Failed to check permission");
GlobalUnLock(); GlobalUnLock();
return ret; return ret;
} }
...@@ -356,7 +356,7 @@ The development procedure is as follows: ...@@ -356,7 +356,7 @@ The development procedure is as follows:
bool isUpdate; bool isUpdate;
int32_t ret = GetIsUpdate(&isUpdate); int32_t ret = GetIsUpdate(&isUpdate);
if (ret != RESULT_SUCCESS) { if (ret != RESULT_SUCCESS) {
IAM_LOGE("get isUpdate failed"); IAM_LOGE("Failed to get isUpdate");
return ret; return ret;
} }
if (isUpdate) { if (isUpdate) {
...@@ -416,7 +416,7 @@ The development procedure is as follows: ...@@ -416,7 +416,7 @@ The development procedure is as follows:
} }
int32_t ret = GenerateSolutionFunc(solutionIn, &schedulesGet, &scheduleIdNum); int32_t ret = GenerateSolutionFunc(solutionIn, &schedulesGet, &scheduleIdNum);
if (ret != RESULT_SUCCESS) { if (ret != RESULT_SUCCESS) {
IAM_LOGE("generate solution failed"); IAM_LOGE("Failed to generate solution");
GlobalUnLock(); GlobalUnLock();
return ret; return ret;
} }
...@@ -463,7 +463,7 @@ The development procedure is as follows: ...@@ -463,7 +463,7 @@ The development procedure is as follows:
} }
info.token.resize(sizeof(UserAuthTokenHal)); info.token.resize(sizeof(UserAuthTokenHal));
if (memcpy_s(&info.token[0], info.token.size(), &authTokenHal, sizeof(authTokenHal)) != EOK) { if (memcpy_s(&info.token[0], info.token.size(), &authTokenHal, sizeof(authTokenHal)) != EOK) {
IAM_LOGE("copy authToken failed"); IAM_LOGE("Failed to copy authToken");
DestoryBuffer(scheduleResultBuffer); DestoryBuffer(scheduleResultBuffer);
GlobalUnLock(); GlobalUnLock();
return RESULT_BAD_COPY; return RESULT_BAD_COPY;
......
...@@ -6,7 +6,7 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri ...@@ -6,7 +6,7 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri
## Development<a name="section13857170163412"></a> ## Development<a name="section13857170163412"></a>
1. Complete the operations described in [Getting Started with Hi3861](../quick-start/quickstart-lite-introduction-hi3861.md#section19352114194115). 1. Complete the operations described in [Getting Started with Hi3861](../quick-start/quickstart-lite-overview.md).
LED control examples are stored in the file **applications/sample/wifi-iot/app/iothardware/led\_example.c**. LED control examples are stored in the file **applications/sample/wifi-iot/app/iothardware/led\_example.c**.
...@@ -73,7 +73,6 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri ...@@ -73,7 +73,6 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri
break; break;
} }
} }
return NULL;
} }
``` ```
...@@ -97,7 +96,7 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri ...@@ -97,7 +96,7 @@ Based on the Hi3861 platform, the OpenHarmony WLAN module provides abundant peri
## Verification<a name="section1949121910344"></a> ## Verification<a name="section1949121910344"></a>
For details about the compilation and burning processes, see [Building Source Code](../quick-start/quickstart-lite-steps-hi3861-connection.md#section191121332125319) and [Burning Images](../quick-start/quickstart-lite-steps-hi3861-connection.md#section3288165814218) in the _Getting Started with Hi3861_. For details about the compilation and burning processes, see [Building](../quick-start/quickstart-lite-steps-hi3861-building.md) and [Burning](../quick-start/quickstart-lite-steps-hi3861-burn.md).
After the preceding two steps are complete, press the **RST** button to reset the module. If the LED blinks periodically as expected, the verification is passed. After the preceding two steps are complete, press the **RST** button to reset the module. If the LED blinks periodically as expected, the verification is passed.
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
## Overview<a name="section6614133913129"></a> ## Overview
The OpenHarmony lightweight kernel is a next-generation kernel that evolved from the kernel of Huawei LiteOS, a lightweight IoT operating system. The kernel comes with two patterns: LiteOS-M and LiteOS-A. The LiteOS-M kernel is designed for the mini system, which supports KB-level MCU memory and MPU isolation. Typical counterparts in the industry include FreeRTOS and ThreadX. The LiteOS-A kernel is ideal for the small system, which supports MB-level memory and MMU isolation. Equivalent kernels include Zircon and Darwin. The OpenHarmony lightweight kernel is a next-generation kernel that evolved from the kernel of Huawei LiteOS, a lightweight IoT operating system. The kernel comes with two patterns: LiteOS-M and LiteOS-A. The LiteOS-M kernel is designed for the mini system, which supports a Microcontroller Unit (MCU), memory of kilobytes, and Memory Protection Unit (MPU) isolation. Typical counterparts in the industry include FreeRTOS and ThreadX. The LiteOS-A kernel is ideal for the small system, which supports memory of megabytes and Memory Management Unit (MMU) isolation. Equivalent kernels include Zircon and Darwin.
>![](../public_sys-resources/icon-note.gif) **NOTE:** >![](../public_sys-resources/icon-note.gif) **NOTE:**
>OpenHarmony provides different kernels for different systems. The small system supports LiteOS and Linux. This document applies to the LiteOS-A kernel. For details about operations related to the Linux kernel, see [Linux Kernel Overview](kernel-standard-overview.md). >OpenHarmony provides different kernels for different systems. The small system supports LiteOS and Linux. This document applies to the LiteOS-A kernel. For details about operations related to the Linux kernel, see [Linux Kernel Overview](kernel-standard-overview.md).
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## Introduction<a name="section11660541593"></a> ## Introduction<a name="section11660541593"></a>
ArkCompiler is a built-in componentized and configurable multi-language compilation and runtime platform of OpenHarmony. It contains core components such as the compiler, toolchain, and runtime. It supports compilation and running of high-level programming languages on the multi-chip platform. It accelerates the running of the OpenHarmony standard operating system and its applications and services on mobile phones, PCs, tablets, TVs, automobiles, and smart wearables. ArkCompiler JS Runtime provides the capability of compiling and running the JavaScript (JS) language on the OpenHarmony operating system. ArkCompiler is a built-in componentized and configurable multi-language compilation and runtime platform of OpenHarmony. It contains core components such as the compiler, toolchain, and runtime. It supports compilation and running of high-level programming languages on the multi-chip platform. It accelerates the running of the OpenHarmony standard system and its applications and services on mobile phones, PCs, tablets, TVs, automobiles, and smart wearables. ArkCompiler JS Runtime provides the capability of compiling and running the JavaScript (JS) language on the OpenHarmony operating system.
ArkCompiler JS Runtime consists of two parts: JS compiler toolchain and JS runtime. The JS compiler toolchain compiles JS source code into ArkCompiler bytecodes. The JS runtime executes the generated ArkCompiler bytecodes. Unless otherwise specified, bytecodes refer to ArkCompiler bytecodes in this document. ArkCompiler JS Runtime consists of two parts: JS compiler toolchain and JS runtime. The JS compiler toolchain compiles JS source code into ArkCompiler bytecodes. The JS runtime executes the generated ArkCompiler bytecodes. Unless otherwise specified, bytecodes refer to ArkCompiler bytecodes in this document.
...@@ -20,21 +20,21 @@ ArkCompiler JS Runtime runs ArkCompiler bytecode files to implement JS semantic ...@@ -20,21 +20,21 @@ ArkCompiler JS Runtime runs ArkCompiler bytecode files to implement JS semantic
ArkCompiler JS Runtime consists of four subsystems: ArkCompiler JS Runtime consists of four subsystems:
- Core Subsystem - Core subsystem
Core Subsystem consists of basic language-irrelevant runtime libraries, including ArkCompiler File, Tooling, and ArkCompiler Base. ArkCompiler File provides bytecodes. Tooling supports Debugger. ArkCompiler Base is responsible for implementing system calls. The core subsystem consists of basic language-irrelevant runtime libraries, including ArkCompiler File, Tooling, and ArkCompiler Base. ArkCompiler File provides bytecodes. Tooling supports Debugger. ArkCompiler Base is responsible for implementing system calls.
- JS Execution Subsystem - JS execution subsystem
JS Execution Subsystem consists of an interpreter that executes bytecodes, inline caching that stores hidden classes, and Profiler that analyzes and records runtime types. JS Execution subsystem consists of an interpreter that executes bytecodes, inline caching that stores hidden classes, and Profiler that analyzes and records runtime types.
- JS Compiler Subsystem - JS compiler subsystem
JS Compiler Subsystem consists of the Stub compiler, optimized compilation framework based on the Circuit IR, and code generator. The JS compiler subsystem consists of the Stub compiler, optimized compilation framework based on the Circuit IR, and code generator.
- JS Runtime subsystem - JS runtime subsystem
JS Runtime Subsystem contains various modules related to JS runtime: The JS runtime subsystem contains various modules related to JS runtime:
- Memory management: object allocator and garbage collector (CMS-GC and Partial-Compressing-GC for concurrent marking and partial memory compression) - Memory management: object allocator and garbage collector (CMS-GC and Partial-Compressing-GC for concurrent marking and partial memory compression)
- Analysis tools: DFX tool and CPU and heap profiling tool - Analysis tools: DFX tool and CPU and heap profiling tool
- Concurrency management: abc file manager in the actor concurrency model - Concurrency management: abc file manager in the actor concurrency model
......
# Location
## Introduction
People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by OpenHarmony, mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
Basic Concepts
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
- **Coordinate**
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
- **GNSS positioning**
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
- **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
- **WLAN or Bluetooth positioning**
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
## Directory Structure<a name="section161941989596"></a>
```
/base/location # Source code of the location subsystem
├── etc # Code for the service startup configuration
├── interfaces # APIs
├── profile # Code for service declaration
├── location_common # Common code
├── location_locator # Location service management code
├── location_gnss # GNSS positioning service code
├── location_network # Network positioning service code
├── location_passive # Passive positioning service code
├── location_geocode # Geocoding service code
├── test # Test code
├── utils # Common utility code
```
## Constraints<a name="section119744591305"></a>
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
## Usage
### Available APIs<a name="section1551164914237"></a>
The following table describes APIs available for obtaining device location information.
**Table 1** APIs for obtaining device location information
| API| Description|
| -------- | -------- |
| on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;) : void | Registers a listener for location changes with a location request initiated.|
| off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void | Unregisters the listener for location changes with the corresponding location request deleted.|
| on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Registers a listener for location service status change events.|
| off(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Unregisters the listener for location service status change events.|
| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Registers a listener for cached GNSS location reports.|
| off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Unregisters the listener for cached GNSS location reports.|
| on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void; | Registers a listener for satellite status change events.|
| off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void; | Unregisters the listener for satellite status change events.|
| on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;) : void; | Registers a listener for GNSS NMEA message change events.|
| off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;) : void; | Unregisters the listener for GNSS NMEA message change events.|
| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence.|
| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence.|
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;) : void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest) : Promise&lt;Location&gt; | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(callback: AsyncCallback&lt;Location&gt;) : void | Obtains the previous location. This API uses an asynchronous callback to return the result.|
| getLastLocation() : Promise&lt;Location&gt; | Obtains the previous location. This API uses a promise to return the result. |
| isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.|
| isLocationEnabled() : Promise&lt;boolean&gt; | Checks whether the location service is enabled. This API uses a promise to return the result.|
| requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result.|
| requestEnableLocation() : Promise&lt;boolean&gt; | Requests to enable the location service. This API uses a promise to return the result.|
| enableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Enables the location service. This API uses an asynchronous callback to return the result.|
| enableLocation() : Promise&lt;boolean&gt; | Enables the location service. This API uses a promise to return the result.|
| disableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Disables the location service. This API uses an asynchronous callback to return the result.|
| disableLocation() : Promise&lt;boolean&gt; | Disables the location service. This API uses a promise to return the result.|
| getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result.|
| getCachedGnssLocationsSize() : Promise&lt;number&gt;; | Obtains the number of cached GNSS locations. This API uses a promise to return the result.|
| flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.|
| flushCachedGnssLocations() : Promise&lt;boolean&gt;; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.|
| sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.|
| sendCommand(command: LocationCommand) : Promise&lt;boolean&gt;; | Sends extended commands to the location subsystem. This API uses a promise to return the result.|
| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&lt;boolean&gt;) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise&lt;boolean&gt;; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback&lt;boolean&gt;) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise&lt;boolean&gt;; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.|
### How to Use<a name="section129654513264"></a>
**Obtaining the device location information:**
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user.
The system provides the following location permissions:
- ohos.permission.LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information.
If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background.
To allow your application to access device location information, you can declare the required permissions in the **config.json** file of your application. The sample code is as follows:
```
{
"module": {
"reqPermissions": [{
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_description",
"usedScene": {
"ability": ["com.myapplication.LocationAbility"],
"when": "inuse"
}, {
...
}
]
}
}
```
For details about the configuration fields, see the description of the **module.json** file.
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
```
import geolocation from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
**Method 1:**
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
```
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
**Table 2** Common use cases of the location function
| Use Case| Constant| Description|
| -------- | -------- | -------- |
| Navigation| NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency| NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
The following example instantiates the **RequestParam** object for navigation:
```
var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
```
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
**Table 3** Location priority policies
| Policy| Constant| Description|
| -------- | -------- | -------- |
| Location accuracy priority| ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority| FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.|
The following example instantiates the **RequestParam** object for the location accuracy priority policy:
```
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic.
```
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start device location.
```
geolocation.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```
geolocation.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```
geolocation.getLastLocation((data) => {
console.log('getLastLocation: data: ' + JSON.stringify(data));
});
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
**Converting the coordinates and geocoding information:**
> **NOTE**
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```
import geolocation from '@ohos.geolocation';
```
2. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data));
});
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see the *API Reference*.
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data));
});
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the *API Reference*.
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
## Repositories Involved
Location subsystem
[base_location](https://gitee.com/openharmony/base_location)
文件模式从 100755 更改为 100644
# DataShare开发指导
DataShare即数据共享模块,提供了向其他应用共享以及管理其数据的方法。目前仅支持同个设备上应用之间的数据共享。
## 接口说明
**表1** 数据提供方API说明
|接口名|描述|
|:------|:------|
|onCreate?(want: Want, callback: AsyncCallback&lt;void&gt;): void|DataShareExtensionAbility生命周期回调,在数据提供方应用创建时回调,执行初始化业务逻辑操作,如创建数据库。|
|insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void|业务函数,在访问方向数据库中插入数据时回调。|
|update?(uri: string, predicates: DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void|业务函数,在访问方更新数据时回调。|
|query?(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void|业务函数,在访问方查询数据时回调。|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void|业务函数,在访问方删除数据时回调。|
完整的数据提供方接口请见[DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md)
**表2** 数据访问方API说明
| 接口名 | 描述 |
| :----------------------------------------------------------- | :--------------------------------- |
| createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void | 创建DataShare工具类。 |
| insert(uri: string, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void | 将单条数据记录插入数据库。 |
| update(uri: string, predicates: DataSharePredicates, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void | 更新数据库中的数据记录。 |
| query(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;DataShareResultSet&gt;): void | 查询数据库中的数据。 |
| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void | 从数据库中删除一条或多条数据记录。 |
完整的数据访问方接口请见[DataShareHelper](../reference/apis/js-apis-data-dataShare.md)
## 开发场景
数据共享可分为数据的提供方和访问方两部分。
- 提供方可以选择性实现数据的增、删、改、查,以及文件打开等功能,并对外共享这些数据。
- 访问方利用工具类,便可以访问提供方提供的这些数据。
以下是数据提供方和数据访问方应用的各自开发示例。
### 数据提供方应用的开发(仅限系统应用)
1. 导入基础依赖包。
```ts
import Extension from '@ohos.application.DataShareExtensionAbility'
import rdb from '@ohos.data.rdb';
import fileIo from '@ohos.fileio'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
```
2. 数据提供方(也称服务端)继承于DataShareExtensionAbility,开发者可根据应用需求选择性重写其业务实现。例如数据提供方只提供查询服务,则可只重写查询接口。
3. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。
```ts
let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore;
let result;
export default class DataShareExtAbility extends Extension {
private rdbStore_;
// 重写onCreate接口
onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'
// 业务实现使用RDB
rdb.getRdbStore(this.context, {
name: DB_NAME
}, 1, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
});
callback();
});
}
// 重写query接口
query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) {
console.info('invalid predicates');
}
try {
rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
if (resultSet != undefined) {
console.info('resultSet.rowCount: ' + resultSet.rowCount);
}
if (callback != undefined) {
callback(err, resultSet);
}
});
} catch (err) {
console.error('error' + err);
}
}
// 可根据应用需求,选择性重写各个接口
// ...
};
```
4. 在module.json5中定义DataShareExtensionAbility。
| Json重要字段 | 备注说明 |
| ------------ | ------------------------------------------------------------ |
| "name" | Ability名称,对应Ability派生的ExtensionAbility类名。 |
| "type" | Ability类型,DataShare对应的Ability类型为”dataShare“,表示基于datashare模板开发的。 |
| "uri" | 通信使用的URI,是客户端链接服务端的唯一标识。 |
| "visible" | 对其他应用是否可见,设置为true时,才能与其他应用进行通信传输数据。 |
**module.json5配置样例**
```json
"extensionAbilities": [
{
"srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts",
"name": "DataShareExtAbility",
"icon": "$media:icon",
"description": "$string:description_datashareextability",
"type": "dataShare",
"uri": "datashare://com.samples.datasharetest.DataShare",
"visible": true
}
]
```
### 数据访问方应用的开发
1. 导入基础依赖包。
```ts
import Ability from '@ohos.application.Ability'
import dataShare from '@ohos.data.dataShare'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
```
2. 定义与数据提供方通信的URI字符串。
```ts
// 作为参数传递的URI,与module.json5中定义的URI的区别是多了一个"/",是因为作为参数传递的URI中,在第二个与第三个"/"中间,存在一个DeviceID的参数
let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
```
2. 创建工具接口类对象。
```ts
let dsHelper;
let abilityContext;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{
dsHelper = data;
});
}
}
```
3. 获取到接口类对象后,便可利用其提供的接口访问提供方提供的服务,如进行数据的增删改查等。
```ts
// 构建一条数据
var valuesBucket = {"name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1,2,3])};
var updateBucket = {"name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1,2,3])};
let da = new dataSharePredicates.DataSharePredicates();
var valArray =new Array("*");
let people = new Array(
{"name": "LiSi", "age": 41, "Binary": ar},
{"name": "WangWu", "age": 21, "Binary": arr},
{"name": "ZhaoLiu", "age": 61, "Binary": arr});
// 插入一条数据
dsHelper.insert(dseUri, valuesBucket, (err,data) => {
console.log("dsHelper insert result: " + data);
});
// 删除指定的数据
dsHelper.delete(dseUri, da, (err,data) => {
console.log("dsHelper delete result: " + data);
});
// 更新数据
dsHelper.update(dseUri, da, updateBucket, (err,data) => {
console.log("dsHelper update result: " + data);
});
// 查询数据
dsHelper.query(dseUri, da, valArray, (err,data) => {
console.log("dsHelper query result: " + data);
});
```
# 数据共享开发概述
## 数据共享简介
DataShare即数据共享模块,用于应用管理其自身数据,也提供了向其他应用共享以及管理其数据的方法。目前仅支持同个设备上应用之间的数据共享。
在许多应用场景中都需要用到数据共享,比如将电话簿、短信、媒体库中的数据共享给其他应用等。当然,不是所有的数据都允许其他应用访问,比如帐号、密码等;有些数据也只允许其他应用查询而不允许其删改,比如短信等。所以对于各种数据共享场景,DataSahre这样一个安全、便捷的可以跨设备、跨应用的数据共享机制是十分必需的。
对于数据提供者来说,无需进行繁琐的封装,可直接使用DataShare框架实现向其他应用共享数据;对于数据访问方来说,因DataShare的访问方式不会因数据提供的方式而不同,所以只需要学习和使用一套接口即可,大大减少了学习时间和开发难度。
## 基本概念
在进行应用的开发前,开发者应了解以下基本概念:
- 数据提供方
提供数据及实现相关业务的应用程序,也称为生产者或服务端。
- 数据访问方
访问数据提供方所提供的数据或业务的应用程序,也称为消费者或客户端。
- 数据集
用户要插入的数据集合,可以是一条或多条数据。数据集以键值对的形式存在,键为字符串类型,值支持数字、字符串、布尔值、无符号整型数组等多种数据类型。
- 结果集
用户查询之后的结果集合,其提供了灵活的数据访问方式,以便用户获取各项数据。
- 谓词
用户访问数据库中的数据所使用的筛选条件,经常被应用在更新数据、删除数据和查询数据中等场景。
## 运作机制
**图 1** DataShare运作机制<a name="fig3330103712254"></a>
![](figures/zh-cn_DataShare.png)
- DataShareExtAbility模块为数据提供方,实现跨应用数据共享的相关业务。
- DataShareHelper模块为数据访问方,提供各种访问数据的接口,包括增删改查等。
- 数据访问方与提供方通过IPC进行通信,数据提供方可以通过数据库实现,也可以通过其他数据存储方式实现。
- ResultSet模块通过共享内存实现,用于存储查询数据得到的结果集,并提供了遍历结果集的方法。
## 约束与限制
- DataShare受到数据提供方所使用数据库的一些限制。例如支持的数据模型、Key的长度、Value的长度、每个应用程序支持同时打开数据库的最大数量等,都会受到使用的数据库的限制。
- 因DataShare内部实现依赖于IPC通信,所以数据集、谓词、结果集等的载荷受到IPC通信的约束与限制。
...@@ -15,41 +15,41 @@ ...@@ -15,41 +15,41 @@
**表1** 获取位置信息API功能介绍 **表1** 获取位置信息API功能介绍
| 接口名 | 功能描述 | | 接口名 | 功能描述 |
| -------- | -------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| on(type:&nbsp;'locationChange',&nbsp;request:&nbsp;LocationRequest,&nbsp;callback:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | 开启位置变化订阅,并发起定位请求。 | | on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;) : void | 开启位置变化订阅,并发起定位请求。 |
| off(type:&nbsp;'locationChange',&nbsp;callback?:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | 关闭位置变化订阅,并删除对应的定位请求。 | | off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void | 关闭位置变化订阅,并删除对应的定位请求。 |
| on(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | 订阅位置服务状态变化。 | | on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | 订阅位置服务状态变化。 |
| off(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | 取消订阅位置服务状态变化。 | | off(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | 取消订阅位置服务状态变化。 |
| on(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;request:&nbsp;CachedGnssLoactionsRequest,&nbsp;callback:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | 订阅缓存GNSS位置上报。 | | on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void; | 订阅缓存GNSS位置上报。 |
| off(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;callback?:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | 取消订阅缓存GNSS位置上报。 | | off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void; | 取消订阅缓存GNSS位置上报。 |
| on(type:&nbsp;'gnssStatusChange',&nbsp;callback:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | 订阅卫星状态信息更新事件。 | | on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void; | 订阅卫星状态信息更新事件。 |
| off(type:&nbsp;'gnssStatusChange',&nbsp;callback?:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | 取消订阅卫星状态信息更新事件。 | | off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void; | 取消订阅卫星状态信息更新事件。 |
| on(type:&nbsp;'nmeaMessageChange',&nbsp;callback:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | 订阅GNSS&nbsp;NMEA信息上报。 | | on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;) : void; | 订阅GNSS NMEA信息上报。 |
| off(type:&nbsp;'nmeaMessageChange',&nbsp;callback?:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | 取消订阅GNSS&nbsp;NMEA信息上报。 | | off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;) : void; | 取消订阅GNSS NMEA信息上报。 |
| on(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | 添加围栏,并订阅该围栏事件上报。 | | on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | 添加围栏,并订阅该围栏事件上报。 |
| off(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | 删除围栏,并取消订阅该围栏事件。 | | off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | 删除围栏,并取消订阅该围栏事件。 |
| getCurrentLocation(request:&nbsp;CurrentLocationRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | 获取当前位置,使用callback回调异步返回结果。 | | getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;) : void | 获取当前位置,使用callback回调异步返回结果。 |
| getCurrentLocation(request?:&nbsp;CurrentLocationRequest)&nbsp;:&nbsp;Promise&lt;Location&gt; | 获取当前位置,使用Promise方式异步返回结果。 | | getCurrentLocation(request?: CurrentLocationRequest) : Promise&lt;Location&gt; | 获取当前位置,使用Promise方式异步返回结果。 |
| getLastLocation(callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | 获取上一次位置,使用callback回调异步返回结果。 | | getLastLocation(callback: AsyncCallback&lt;Location&gt;) : void | 获取上一次位置,使用callback回调异步返回结果。 |
| getLastLocation()&nbsp;:&nbsp;Promise&lt;Location&gt; | 获取上一次位置,使用Promise方式异步返回结果。 | | getLastLocation() : Promise&lt;Location&gt; | 获取上一次位置,使用Promise方式异步返回结果。 |
| isLocationEnabled(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 判断位置服务是否已经打开,使用callback回调异步返回结果。 | | isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;) : void | 判断位置服务是否已经打开,使用callback回调异步返回结果。 |
| isLocationEnabled()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 判断位置服务是否已经开启,使用Promise方式异步返回结果。 | | isLocationEnabled() : Promise&lt;boolean&gt; | 判断位置服务是否已经开启,使用Promise方式异步返回结果。 |
| requestEnableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 请求打开位置服务,使用callback回调异步返回结果。 | | requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | 请求打开位置服务,使用callback回调异步返回结果。 |
| requestEnableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 请求打开位置服务,使用Promise方式异步返回结果。 | | requestEnableLocation() : Promise&lt;boolean&gt; | 请求打开位置服务,使用Promise方式异步返回结果。 |
| enableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 打开位置服务,使用callback回调异步返回结果。 | | enableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | 打开位置服务,使用callback回调异步返回结果。 |
| enableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 打开位置服务,使用Promise方式异步返回结果。 | | enableLocation() : Promise&lt;boolean&gt; | 打开位置服务,使用Promise方式异步返回结果。 |
| disableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | 关闭位置服务,使用callback回调异步返回结果。 | | disableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | 关闭位置服务,使用callback回调异步返回结果。 |
| disableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | 关闭位置服务,使用Promise方式异步返回结果。 | | disableLocation() : Promise&lt;boolean&gt; | 关闭位置服务,使用Promise方式异步返回结果。 |
| getCachedGnssLocationsSize(callback:&nbsp;AsyncCallback&lt;number&gt;)&nbsp;:&nbsp;void; | 获取缓存GNSS位置的个数,使用callback回调异步返回结果。 | | getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;) : void; | 获取缓存GNSS位置的个数,使用callback回调异步返回结果。 |
| getCachedGnssLocationsSize()&nbsp;:&nbsp;Promise&lt;number&gt;; | 获取缓存GNSS位置的个数,使用Promise方式异步返回结果。 | | getCachedGnssLocationsSize() : Promise&lt;number&gt;; | 获取缓存GNSS位置的个数,使用Promise方式异步返回结果。 |
| flushCachedGnssLocations(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用callback回调异步返回结果。 | | flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;) : void; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用callback回调异步返回结果。 |
| flushCachedGnssLocations()&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用Promise方式异步返回结果。 | | flushCachedGnssLocations() : Promise&lt;boolean&gt;; | 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用Promise方式异步返回结果。 |
| sendCommand(command:&nbsp;LocationCommand,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 给位置服务子系统发送扩展命令,使用callback回调异步返回结果。 | | sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;) : void; | 给位置服务子系统发送扩展命令,使用callback回调异步返回结果。 |
| sendCommand(command:&nbsp;LocationCommand)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 给位置服务子系统发送扩展命令,使用Promise方式异步返回结果。 | | sendCommand(command: LocationCommand) : Promise&lt;boolean&gt;; | 给位置服务子系统发送扩展命令,使用Promise方式异步返回结果。 |
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 查询用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 | | isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&lt;boolean&gt;) : void; | 查询用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 |
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 查询用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 | | isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise&lt;boolean&gt;; | 查询用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 |
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | 设置并记录用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 | | setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback&lt;boolean&gt;) : void; | 设置并记录用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。 |
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | 设置并记录用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 | | setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise&lt;boolean&gt;; | 设置并记录用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。 |
## 开发步骤 ## 开发步骤
...@@ -113,7 +113,7 @@ ...@@ -113,7 +113,7 @@
**表2** 定位场景类型说明 **表2** 定位场景类型说明
| 场景名称 | 常量定义 | 说明 | | 场景名称 | 常量定义 | 说明 |
| -------- | -------- | -------- | | ------------ | ------------------- | ------------------------------------------------------------ |
| 导航场景 | NAVIGATION | 适用于在户外定位设备实时位置的场景,如车载、步行导航。在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。<br/>此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 导航场景 | NAVIGATION | 适用于在户外定位设备实时位置的场景,如车载、步行导航。在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。<br/>此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 轨迹跟踪场景 | TRAJECTORY_TRACKING | 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 轨迹跟踪场景 | TRAJECTORY_TRACKING | 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 出行约车场景 | CAR_HAILING | 适用于用户出行打车时定位当前位置的场景,如网约车类应用。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 出行约车场景 | CAR_HAILING | 适用于用户出行打车时定位当前位置的场景,如网约车类应用。<br/>此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
...@@ -144,7 +144,7 @@ ...@@ -144,7 +144,7 @@
**表3** 定位优先级策略类型说明: **表3** 定位优先级策略类型说明:
| 策略类型 | 常量定义 | 说明 | | 策略类型 | 常量定义 | 说明 |
| -------- | -------- | -------- | | ------------------ | -------------- | ------------------------------------------------------------ |
| 定位精度优先策略 | ACCURACY | 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 定位精度优先策略 | ACCURACY | 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 快速定位优先策略 | FAST_FIRST_FIX | 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 快速定位优先策略 | FAST_FIRST_FIX | 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。<br/>应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。 |
| 低功耗定位优先策略 | LOW_POWER | 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。<br/>应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 | | 低功耗定位优先策略 | LOW_POWER | 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。<br/>应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。 |
......
...@@ -56,7 +56,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建 ...@@ -56,7 +56,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建
3. **定义回调函数OnSurfaceCreated**。用于在`Surface`创建时,通过回调函数初始化开发者的渲染环境,例如`Skia`渲染环境。并将要显示的内容写入`NativeWindow` 3. **定义回调函数OnSurfaceCreated**。用于在`Surface`创建时,通过回调函数初始化开发者的渲染环境,例如`Skia`渲染环境。并将要显示的内容写入`NativeWindow`
```c++ ```c++
void OnSufaceCreatedCB(NativeXComponent* component, void* window) { void OnSurfaceCreatedCB(NativeXComponent* component, void* window) {
//获取 native window 的宽高 //获取 native window 的宽高
uint64_t width_ = 0, height_ = 0; uint64_t width_ = 0, height_ = 0;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_); OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
...@@ -89,8 +89,8 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建 ...@@ -89,8 +89,8 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建
//创建 Skia Canvas 并将内容写入naitve window //创建 Skia Canvas 并将内容写入naitve window
... ...
//写入完成后,通过OH_NativeWindwo_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上 //写入完成后,通过OH_NativeWindow_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上
Regoin region{nullptr, 0}; Region region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region) OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
} }
``` ```
...@@ -99,9 +99,9 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建 ...@@ -99,9 +99,9 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建
```c++ ```c++
OH_NativeXComponent_Callback &callback_; OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB; callback_->OnSurfaceCreated = OnSurfaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB; callback_->OnSurfaceChanged = OnSurfaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB; callback_->OnSurfaceDestoryed = OnSurfaceDestoryedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB; callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_) OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
``` ```
...@@ -336,6 +336,7 @@ abilities描述ability的配置信息,标签值为数组类型。 ...@@ -336,6 +336,7 @@ abilities描述ability的配置信息,标签值为数组类型。
|minWindowWidth|表示该ability支持的最小的窗口宽度, 宽度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口宽度。| |minWindowWidth|表示该ability支持的最小的窗口宽度, 宽度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口宽度。|
|maxWindowHeight|表示该ability支持的最大的窗口高度, 高度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口高度。| |maxWindowHeight|表示该ability支持的最大的窗口高度, 高度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口高度。|
|minWindowHeight|表示该ability支持的最小的窗口高度, 高度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口高度。| |minWindowHeight|表示该ability支持的最小的窗口高度, 高度单位为pixl。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口高度。|
| excludeFromMissions | 该标签标识ability是否在最近任务列表中显示,仅支持系统应用配置。为布尔类型,true表示不在任务列表中显示,false表示在任务列表中显示。 | 布尔值 | 该标签可缺省,缺省值为false。|
abilities示例 abilities示例
...@@ -344,7 +345,7 @@ abilities示例 ...@@ -344,7 +345,7 @@ abilities示例
"abilities": [{ "abilities": [{
"name": "MainAbility", "name": "MainAbility",
"srcEntrance": "./ets/login/MyLoginAbility.ts", "srcEntrance": "./ets/login/MyLoginAbility.ts",
"launchType":"standard" "launchType":"standard",
"description": "$string:description_main_ability", "description": "$string:description_main_ability",
"icon": "$media:icon", "icon": "$media:icon",
"label": "Login", "label": "Login",
...@@ -378,8 +379,9 @@ abilities示例 ...@@ -378,8 +379,9 @@ abilities示例
"maxWindowWidth": 2560, "maxWindowWidth": 2560,
"minWindowWidth": 1400, "minWindowWidth": 1400,
"maxWindowHeight": 300, "maxWindowHeight": 300,
"minWindowHeight": 200 "minWindowHeight": 200,
}], "excludeFromMissions": false
}]
} }
``` ```
......
...@@ -77,6 +77,7 @@ ...@@ -77,6 +77,7 @@
- [@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.display (屏幕属性)](js-apis-display.md) - [@ohos.display (屏幕属性)](js-apis-display.md)
......
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
本模块提供应用信息查询能力,支持BundleInfo、ApplicationInfo、Ability、ExtensionAbility、应用状态等信息的查询 本模块提供应用信息查询能力,支持BundleInfo、ApplicationInfo、Ability、ExtensionAbility、应用状态等信息的查询
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> API9 当前为Canary版本,仅供试用,不保证接口可稳定调用。 > API9 当前为Canary版本,仅供试用,不保证接口可稳定调用。
## 导入模块 ## 导入模块
...@@ -22,6 +23,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -22,6 +23,7 @@ SystemCapability.BundleManager.BundleFramework
| ohos.permission.GET_BUNDLE_INFO | normal | 查询指定应用信息 | | ohos.permission.GET_BUNDLE_INFO | normal | 查询指定应用信息 |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 |
| ohos.permission.INSTALL_BUNDLE | system_core | 可安装、卸载应用 | | ohos.permission.INSTALL_BUNDLE | system_core | 可安装、卸载应用 |
| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | 可设置和查询应用的处置状态 |
权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) 权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E)
...@@ -71,7 +73,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId) ...@@ -71,7 +73,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId)
getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\<ApplicationInfo>): void getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\<ApplicationInfo>): void
以异步方法根据给定的包名获取ApplicationInfo,使用callback形式返回结果。 以异步方法根据给定的包名获取指定用户下的ApplicationInfo,使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -219,7 +221,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { ...@@ -219,7 +221,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => {
getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback<Array\<BundleInfo>>): void getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback<Array\<BundleInfo>>): void
以异步方法获取系统中所有可用的BundleInfo,使用callback形式返回结果。 以异步方法获取系统中指定用户下所有可用的BundleInfo,使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -456,7 +458,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ...@@ -456,7 +458,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => {
getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback<Array\<ApplicationInfo>>) : void; getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback<Array\<ApplicationInfo>>) : void;
获取指定用户下所有已安装的应用信息,使用callback形式返回结果。 获取所有已安装的应用信息,使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -1048,7 +1050,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) ...@@ -1048,7 +1050,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId)
queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback<Array\<AbilityInfo>>): void queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback<Array\<AbilityInfo>>): void
以异步方法根据给定的意图获取Ability信息,使用callback形式返回结果。 以异步方法根据给定的意图获取获取指定用户下Ability信息,使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -1266,7 +1268,7 @@ bundle.getNameForUid(uid, (err, data) => { ...@@ -1266,7 +1268,7 @@ bundle.getNameForUid(uid, (err, data) => {
getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>; getAbilityIcon(bundleName: string, abilityName: string): Promise\<image.PixelMap>;
以异步方法通过bundleName和abilityName获取对应Icon的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用Promise形式返回结果。 以异步方法通过bundleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用Promise形式返回结果。
**需要权限:** **需要权限:**
...@@ -1286,7 +1288,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1286,7 +1288,7 @@ SystemCapability.BundleManager.BundleFramework
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| --------------------- | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------------ |
| Promise\<image.PixelMap> | 返回值为[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)。 | | Promise\<image.PixelMap> | 返回值为[PixelMap](js-apis-image.md)。 |
**示例:** **示例:**
...@@ -1305,7 +1307,7 @@ bundle.getAbilityIcon(bundleName, abilityName) ...@@ -1305,7 +1307,7 @@ bundle.getAbilityIcon(bundleName, abilityName)
getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void; getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void;
以异步方法通过bundleName和abilityName获取对应Icon的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用callback形式返回结果。 以异步方法通过bundleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -1321,7 +1323,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1321,7 +1323,7 @@ SystemCapability.BundleManager.BundleFramework
| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | | ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 要查询的bundleName。 | | bundleName | string | 是 | 要查询的bundleName。 |
| abilityName | string | 是 | 要查询的abilityName。 | | abilityName | string | 是 | 要查询的abilityName。 |
| callback | AsyncCallback\<image.PixelMap> | 是 | 程序启动作为入参的回调函数,返回指定[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)。 | | callback | AsyncCallback\<image.PixelMap> | 是 | 程序启动作为入参的回调函数,返回指定[PixelMap](js-apis-image.md)。 |
**示例:** **示例:**
...@@ -1341,7 +1343,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ...@@ -1341,7 +1343,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => {
getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise\<image.PixelMap>; getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise\<image.PixelMap>;
以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用Promise形式返回结果。 以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用Promise形式返回结果。
**需要权限:** **需要权限:**
...@@ -1362,7 +1364,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1362,7 +1364,7 @@ SystemCapability.BundleManager.BundleFramework
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| --------------------- | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------------ |
| Promise\<image.PixelMap> | 返回值为[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)。 | | Promise\<image.PixelMap> | 返回值为[PixelMap](js-apis-image.md)。 |
**示例:** **示例:**
...@@ -1382,7 +1384,7 @@ bundle.getAbilityIcon(bundleName, moduleName, abilityName) ...@@ -1382,7 +1384,7 @@ bundle.getAbilityIcon(bundleName, moduleName, abilityName)
getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void; getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\<image.PixelMap>): void;
以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md),使用callback形式返回结果。 以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -1399,7 +1401,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -1399,7 +1401,7 @@ SystemCapability.BundleManager.BundleFramework
| bundleName | string | 是 | 要查询的bundleName。 | | bundleName | string | 是 | 要查询的bundleName。 |
| moduleName | string | 是 | moduleName。 | | moduleName | string | 是 | moduleName。 |
| abilityName | string | 是 | 要查询的abilityName。 | | abilityName | string | 是 | 要查询的abilityName。 |
| callback | AsyncCallback\<image.PixelMap> | 是 | 程序启动作为入参的回调函数,返回指定[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)。 | | callback | AsyncCallback\<image.PixelMap> | 是 | 程序启动作为入参的回调函数,返回指定[PixelMap](js-apis-image.md)。 |
**示例:** **示例:**
...@@ -1469,7 +1471,7 @@ bundle.queryExtensionAbilityInfos(want, extensionType, extensionFlags, userId) ...@@ -1469,7 +1471,7 @@ bundle.queryExtensionAbilityInfos(want, extensionType, extensionFlags, userId)
queryExtensionAbilityInfos(want: Want, extensionType: number, extensionFlags: number, userId: number, callback: AsyncCallback<Array\<ExtensionAbilityInfo>>): void queryExtensionAbilityInfos(want: Want, extensionType: number, extensionFlags: number, userId: number, callback: AsyncCallback<Array\<ExtensionAbilityInfo>>): void
以异步方法根据给定的意图获取ExtensionAbility信息,使用callback形式返回结果。 以异步方法根据给定的意图获取指定用户下的ExtensionAbility信息,使用callback形式返回结果。
**需要权限:** **需要权限:**
...@@ -1593,7 +1595,7 @@ getProfileByAbility(moduleName: string, abilityName: string, metadataName?: stri ...@@ -1593,7 +1595,7 @@ getProfileByAbility(moduleName: string, abilityName: string, metadataName?: stri
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | | ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | | moduleName | string | 是 | 表示要获取的配置文件所属的module。 |
| abilityName | string | 是 | 表示要获取的配置文件所属的ability。 | | abilityName | string | 是 | 表示要获取的配置文件所属的ability。 |
| metadataName | string | 否 | 表示要获取的配置文件所属的[metadata](js-apis-bundle-Metadata.md)。 | | metadataName | string | 否 | 表示要获取的配置文件所属的metadata。 |
**返回值:** **返回值:**
...@@ -1629,7 +1631,7 @@ getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, m ...@@ -1629,7 +1631,7 @@ getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, m
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | | ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | | moduleName | string | 是 | 表示要获取的配置文件所属的module。 |
| extensionAbilityName | string | 是 | 表示要获取的配置文件所属的extensionAbility。 | | extensionAbilityName | string | 是 | 表示要获取的配置文件所属的extensionAbility。 |
| metadataName | string | 是 | 表示要获取的配置文件所属的[metadata](js-apis-bundle-Metadata.md)。 | | metadataName | string | 是 | 表示要获取的配置文件所属的metadata。 |
| callback | AsyncCallback\<Array\<string>> | 是 | 程序启动作为入参的回调函数,返回配置文件的json字符串数组。 | | callback | AsyncCallback\<Array\<string>> | 是 | 程序启动作为入参的回调函数,返回配置文件的json字符串数组。 |
**示例:** **示例:**
...@@ -1681,6 +1683,133 @@ bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataNa ...@@ -1681,6 +1683,133 @@ bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataNa
}) })
``` ```
## bundle.setDisposedStatus<sup>9+</sup>
setDisposedStatus(bundleName: string, status: number, callback: AsyncCallback\<void>): void;
以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用callback形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
**系统能力:** SystemCapability.BundleManager.BundleFramework
**参数:**
| 名称 | 类型 | 必填 | 描述 |
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 表示要被设置处置状态的应用包名。 |
| status | number | 是 | 表示要设置的处置状态值。该值预留用于应用市场设置应用的处置状态,默认为0,不做处置。 |
| callback | AsyncCallback\<void> | 是 | 程序启动作为入参的回调函数,无返回值。 |
**示例:**
```js
let bundleName = 'com.ohos.camera';
let status = 1;
const caller = function callback(err, data) {
console.error('Operation err is: ' + err);
console.error('Operation result is: ' + data);
}
bundle.setDisposedStatus(bundleName, status, caller)
```
## bundle.setDisposedStatus<sup>9+</sup>
setDisposedStatus(bundleName: string, status: number): Promise\<void>;
以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用Promise形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
**系统能力:** SystemCapability.BundleManager.BundleFramework
**参数:**
| 名称 | 类型 | 必填 | 描述 |
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 表示要被设置处置状态的应用包名。 |
| status | number | 是 | 表示要设置的处置状态值。该值预留用于应用市场设置应用的处置状态,默认为0,不做处置。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------- | ------------------------------ |
| Promise\<void> | Promise形式,无返回值。 |
**示例:**
```js
let bundleName = 'com.ohos.camera';
let status = 1;
bundle.setDisposedStatus(bundleName, status).then(data=>{
console.error('Operation result is: ' + data);
}).catch(err=>{
console.error('Operation err is: ' + err);
})
```
## bundle.getDisposedStatus<sup>9+</sup>
getDisposedStatus(bundleName: string,, callback: AsyncCallback\<number>): void;
以异步方法根据给定的bundleName来获取对应应用的处置状态,使用callback形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
**系统能力:** SystemCapability.BundleManager.BundleFramework
**参数:**
| 名称 | 类型 | 必填 | 描述 |
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 表示要获取处置状态的应用包名。 |
| callback | AsyncCallback\<number> | 是 | 程序启动作为入参的回调函数,返回应用的处置状态值。 |
**示例:**
```js
let bundleName = 'com.ohos.camera';
const caller = function callback(err, data) {
console.error('Operation err is: ' + err);
console.error('Operation result is: ' + data);
}
bundle.getDisposedStatus(bundleName, caller)
```
## bundle.getDisposedStatus<sup>9+</sup>
getDisposedStatus(bundleName: string, status: number): Promise\<void>;
以异步方法根据给定的bundleName来获取对应应用的处置状态,使用Promise形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
**系统能力:** SystemCapability.BundleManager.BundleFramework
**参数:**
| 名称 | 类型 | 必填 | 描述 |
| ---------------- | ---------------------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 表示要获取处置状态的应用包名。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------- | ------------------------------ |
| Promise\<number> | Promise返回应用的处置状态。 |
**示例:**
```js
let bundleName = 'com.ohos.camera';
bundle.getDisposedStatus(bundleName).then(data=>{
console.error('Operation result is: ' + data);
}).catch(err=>{
console.error('Operation err is: ' + err);
})
```
## InstallErrorCode ## InstallErrorCode
**系统能力:** SystemCapability.BundleManager.BundleFramework **系统能力:** SystemCapability.BundleManager.BundleFramework
......
# Context模块 # Context模块
Context模块提供了ability或application的上下文的能力,包括允许访问特定于应用程序的资源、请求和验证权限等并且只能通过ability获得 Context模块提供了ability或application的上下文的能力,包括允许访问特定于应用程序的资源、请求和验证权限等。
> **说明:** > **说明:**
> >
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在FA模型下使用。 > 本模块接口仅可在FA模型下使用。
## 导入模块
```js
import featureAbility from '@ohos.ability.featureAbility'
```
## 使用说明 ## 使用说明
Context对象是在featureAbility中创建实例,并通过featureAbility的getContext()接口返回,因此在使用Context时,必须导入@ohos.ability.featureAbility库。示例如下: Context对象是在featureAbility中创建实例,并通过featureAbility的getContext()接口返回,因此在使用Context时,必须导入@ohos.ability.featureAbility库。示例如下:
......
...@@ -9,11 +9,6 @@ AbilityContext模块提供允许访问特定于ability的资源的能力,包 ...@@ -9,11 +9,6 @@ AbilityContext模块提供允许访问特定于ability的资源的能力,包
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```js
import Ability from '@ohos.application.Ability'
```
## 使用说明 ## 使用说明
在使用AbilityContext的功能前,需要通过Ability子类实例获取。 在使用AbilityContext的功能前,需要通过Ability子类实例获取。
...@@ -27,7 +22,6 @@ class MainAbility extends Ability { ...@@ -27,7 +22,6 @@ class MainAbility extends Ability {
} }
``` ```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
...@@ -36,7 +30,7 @@ class MainAbility extends Ability { ...@@ -36,7 +30,7 @@ class MainAbility extends Ability {
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| abilityInfo | AbilityInfo | 是 | 否 | Abilityinfo相关信息 | | abilityInfo | AbilityInfo | 是 | 否 | Abilityinfo相关信息 |
| currentHapModuleInfo | HapModuleInfo | 是 | 否 | 当前hap包的信息 | | currentHapModuleInfo | HapModuleInfo | 是 | 否 | 当前hap包的信息 |
| config | [Configuration](js-apis-configuration.md) | 是 | 否 | 表示配置信息。 |
## AbilityContext.startAbility ## AbilityContext.startAbility
...@@ -46,6 +40,8 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void ...@@ -46,6 +40,8 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -75,6 +71,8 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void& ...@@ -75,6 +71,8 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -108,6 +106,8 @@ startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;; ...@@ -108,6 +106,8 @@ startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -237,6 +237,128 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes ...@@ -237,6 +237,128 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes
}) })
``` ```
## AbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback<AbilityResult>): void;
启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| callback | AsyncCallback\<AbilityResult\> | 是 | 启动Ability的回调函数,返回Ability结果。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
this.context.startAbilityWithAccount(want, accountId, (err, data) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
console.log('---------- startAbilityWithAccount success, data: -----------', data);
});
```
## AbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\<void\> | 是 | 启动Ability的回调函数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityForResultWithAccount(want, accountId, options, (err) => {
console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err);
});
```
## AbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult\>;
启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;AbilityResult&gt; | 返回一个Promise,包含Ability结果。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityForResultWithAccount(want, accountId, options)
.then((data) => {
console.log('---------- startAbilityForResultWithAccount success, data: -----------', data);
})
.catch((err) => {
console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err);
})
```
## AbilityContext.terminateSelf ## AbilityContext.terminateSelf
...@@ -348,6 +470,149 @@ terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;; ...@@ -348,6 +470,149 @@ terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;;
) )
``` ```
## AbilityContext.connectAbility
connectAbility(want: Want, options: ConnectOptions): number;
使用AbilityInfo.AbilityType.SERVICE模板将当前能力连接到一个能力。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | 否 | 远端对象实例。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回Ability连接的结果code。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') }
}
const result = this.context.connectAbility(want, options);
console.log('----------- connectAbilityResult: ------------', result);
```
## AbilityContext.connectAbilityWithAccount
connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number;
使用AbilityInfo.AbilityType.SERVICE模板和account将当前能力连接到一个能力。
**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | 否 | 远端对象实例。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回Ability连接的结果code。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') }
}
const result = this.context.connectAbilityWithAccount(want, accountId, options);
console.log('----------- connectAbilityResult: ------------', result);
```
## AbilityContext.disconnectAbility
disconnectAbility(connection: number): Promise\<void>;
已成功连接接口。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| connection | number | 是 | 连接的能力的数字代码。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
**示例:**
```js
var connectionNumber = 0;
this.context.disconnectAbility(connectionNumber).then((data) => {
console.log('disconnectAbility success, data: ', data);
}).catch((err) => {
console.log('disconnectAbility fail, err: ', err);
});
```
## AbilityContext.disconnectAbility
disconnectAbility(connection: number, callback:AsyncCallback\<void>): void;
已成功连接接口。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| connection | number | 是 | 连接的能力的数字代码。 |
| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
**示例:**
```js
var connectionNumber = 0;
this.context.disconnectAbility(connectionNumber, (err) => {
console.log('---------- disconnectAbility fail, err: -----------', err);
});
```
## AbilityContext.startAbilityByCall ## AbilityContext.startAbilityByCall
...@@ -390,6 +655,120 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;; ...@@ -390,6 +655,120 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
} }
``` ```
## AbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void\>): void;
根据account启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| callback | AsyncCallback\<void\> | 是 | 启动Ability的回调函数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
this.context.startAbilityWithAccount(want, accountId, (err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
});
```
## AbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
根据account启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\<void\> | 是 | 启动Ability的回调函数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityWithAccount(want, accountId, options, (err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
});
```
## AbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void\>;
根据account启动Ability(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityWithAccount(want, accountId, options)
.then((data) => {
console.log('---------- startAbilityWithAccount success, data: -----------', data);
})
.catch((err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
})
```
## AbilityContext.requestPermissionsFromUser ## AbilityContext.requestPermissionsFromUser
...@@ -503,6 +882,117 @@ setMissionLabel(label: string): Promise&lt;void&gt; ...@@ -503,6 +882,117 @@ setMissionLabel(label: string): Promise&lt;void&gt;
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
``` ```
## AbilityContext.setMissionIcon
setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void;
设置当前ability的任务标签。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| icon | image.PixelMap | 是 | 在最近的任务中显示的能力图标。 |
| callback | AsyncCallback\<void> | 是 | 指定的回调函数的结果。 |
**示例:**
```js
import image from '@ohos.multimedia.image'
var imagePixelMap;
var color = new ArrayBuffer(0);
var initializationOptions = {
size: {
height: 100,
width: 100
}
};
image.createPixelMap(color, initializationOptions)
.then((data) => {
imagePixelMap = data;
})
.catch((err) => {
console.log('--------- createPixelMap fail, err: ---------', err)
});
this.context.setMissionIcon(imagePixelMap, (err) => {
console.log('---------- setMissionIcon fail, err: -----------', err);
})
```
## AbilityContext.setMissionIcon
setMissionIcon(icon: image.PixelMap): Promise\<void>;
设置当前ability的任务标签。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| icon | image.PixelMap | 是 | 在最近的任务中显示的能力图标。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | 返回一个Promise,包含接口的结果。 |
**示例:**
```js
import image from '@ohos.multimedia.image'
var imagePixelMap;
var color = new ArrayBuffer(0);
var initializationOptions = {
size: {
height: 100,
width: 100
}
};
image.createPixelMap(color, initializationOptions)
.then((data) => {
imagePixelMap = data;
})
.catch((err) => {
console.log('--------- createPixelMap fail, err: ---------', err)
});
this.context.setMissionIcon(imagePixelMap)
.then((data) => {
console.log('-------------- setMissionIcon success, data: -------------', data);
})
.catch((err) => {
console.log('-------------- setMissionIcon fail, err: -------------', err);
});
```
## AbilityContext.restoreWindowStage
restoreWindowStage(localStorage: LocalStorage) : void;
恢复ability中的window stage数据。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| localStorage | image.LocalStorage | 是 | 用于恢复window stage的存储数据。 |
**示例:**
```js
var storage = new LocalStorage();
this.context.restoreWindowStage(storage);
```
## AbilityContext.isTerminating ## AbilityContext.isTerminating
......
...@@ -14,61 +14,63 @@ import wantConstant from '@ohos.ability.wantConstant' ...@@ -14,61 +14,63 @@ import wantConstant from '@ohos.ability.wantConstant'
## wantConstant.Action ## wantConstant.Action
**系统能力**:SystemCapability.Ability.AbilityBase want操作的常数。
权限列表。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 系统公共事件宏 | 系统公共事件名称 | 订阅者所需权限 | | 名称 | 值 | 描述 |
| ------------ | ------------------ | ---------------------- | | ------------ | ------------------ | ---------------------- |
| ACTION_HOME | ohos.want.action.home | 无 | | ACTION_HOME | ohos.want.action.home | 指示返回原点的操作。 |
| ACTION_DIAL | ohos.want.action.dial | 无 | | ACTION_DIAL | ohos.want.action.dial | 指示启动显示小键盘的页面功能的操作 |
| ACTION_SEARCH | ohos.want.action.search | 无 | | ACTION_SEARCH | ohos.want.action.search | 指示启动页面搜索功能的操作。 |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | 无 | | ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | 指示启动提供无线网络设置的页面功能的操作,例如,Wi-Fi选项。 |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | 无 | | ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | 指示启动管理已安装应用程序的页面功能的操作。 |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | 无 | | ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | 指示启动显示指定应用程序详细信息的页面功能的操作。 |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | 无 | | ACTION_SET_ALARM | ohos.want.action.setAlarm | 指示启动页面功能以设置闹钟的操做作。 |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | 无 | | ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | 指示启动显示所有警报的页面功能的操作时钟。 |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | 无 | | ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | 指示启动用于使闹钟睡眠的页面功能的操作。 |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | 无 | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | 指示启动删除闹钟的页面功能的操作。 |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | 无 | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | 指示启动页面功能以关闭计时器的操作。 |
| ACTION_SEND_SMS | ohos.want.action.sendSms | 无 | | ACTION_SEND_SMS | ohos.want.action.sendSms | 指示启动发送sms的页面功能的操作。 |
| ACTION_CHOOSE | ohos.want.action.choose | 无 | | ACTION_CHOOSE | ohos.want.action.choose | 指示启动页面功能以打开联系人或图片的操作。 |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | 无 | | ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | 指示启动页面拍照功能的操作。 |
| ACTION_VIDEO_CAPTUR<sup>8+</sup> | ohos.want.action.videoCapture | 无 | | ACTION_VIDEO_CAPTUR<sup>8+</sup> | ohos.want.action.videoCapture | 指示启动页面功能以拍摄视频的操作。 |
| ACTION_SELECT | ohos.want.action.select | 无 | | ACTION_SELECT | ohos.want.action.select | 指示显示应用程序选择对话框的操作。 |
| ACTION_SEND_DATA | ohos.want.action.sendData | 无 | | ACTION_SEND_DATA | ohos.want.action.sendData | 指示发送单个数据记录的操作。 |
| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | 无 | | ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | 指示发送多个数据记录的操作。 |
| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | 无 | | ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | 指示请求媒体扫描仪扫描文件并将文件添加到媒体库的操作。 |
| ACTION_VIEW_DATA | ohos.want.action.viewData | 无 | | ACTION_VIEW_DATA | ohos.want.action.viewData | 指示查看数据的操作。 |
| ACTION_EDIT_DATA | ohos.want.action.editData | 无 | | ACTION_EDIT_DATA | ohos.want.action.editData | 指示编辑数据的操作。 |
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | 无 | | INTENT_PARAMS_INTENT | ability.want.params.INTENT | 指示将使用连接选取显示的选项的操作。 |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | 无 | | INTENT_PARAMS_TITLE | ability.want.params.TITLE | 指示与连接选取显示的选项一起使用时的字符序列对话框标题。 |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | 无 | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | 指示选择文件的操作。 |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | 无 | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | 指示与连接发送数据一起使用时,包含与意图相关联的数据流的URI。 |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | 无 | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | 指示提供oauth服务的操作。 |
| ACTION_MARKER_DOWNLOAD | ohos.want.action.marketDownload | 表示从应用程序市场下载应用程序的行为。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
## wantConstant.Entity ## wantConstant.Entity
**系统能力**:SystemCapability.Ability.AbilityBase want实体的常数。
权限列表。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 系统公共事件宏 | 系统公共事件名称 | 订阅者所需权限 | | 名称 | 值 | 描述 |
| ------------ | ------------------ | ---------------------- | | ------------ | ------------------ | ---------------------- |
| ENTITY_DEFAULT | entity.system.default | | | ENTITY_DEFAULT | entity.system.default | 指示默认实体,如果未指定该实体,则使用该实体。 |
| ENTITY_HOME | entity.system.homel | | | ENTITY_HOME | entity.system.homel | 指示主屏幕实体。 |
| ENTITY_VOICE | ENTITY_VOICE | 无 | | ENTITY_VOICE | entity.system.voice | 表示语音交互实体。 |
| ENTITY_BROWSABLE | entity.system.browsable | | | ENTITY_BROWSABLE | entity.system.browsable | 指示浏览器类别。 |
| ENTITY_VIDEO | entity.system.video | | | ENTITY_VIDEO | entity.system.video | 指示视频类别。 |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | 无 |
## wantConstant.Flags
## flags说明 Flags说明。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 参数 | 描述 | | 名称 | | 描述 |
| ------------------------------------ | ---------- | ------------------------------------------------------------ | | ------------------------------------ | ---------- | ------------------------------------------------------------ |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | 指示对URI执行读取操作的授权。 | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | 指示对URI执行读取操作的授权。 |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | 指示对URI执行写入操作的授权。 | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | 指示对URI执行写入操作的授权。 |
...@@ -76,10 +78,10 @@ import wantConstant from '@ohos.ability.wantConstant' ...@@ -76,10 +78,10 @@ import wantConstant from '@ohos.ability.wantConstant'
| FLAG_ABILITY_CONTINUATION | 0x00000008 | 确定是否可以将本地设备上的功能迁移到远程设备。 | | FLAG_ABILITY_CONTINUATION | 0x00000008 | 确定是否可以将本地设备上的功能迁移到远程设备。 |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | 指定组件是否属于OHOS。 | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | 指定组件是否属于OHOS。 |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | 指定是否启动某个能力。 | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | 指定是否启动某个能力。 |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | 指示URI上可能持久化的授权。 | | FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | 指示URI上可能持久化的授权。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | 按照前缀匹配的方式验证URI权限。 | | FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | 按照前缀匹配的方式验证URI权限。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | 支持分布式调度系统中的多设备启动。 | | FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | 支持分布式调度系统中的多设备启动。 |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | 指示无论主机应用程序是否已启动,都将启动使用服务模板的功能。 | | FLAG_START_FOREGROUND_ABILITY | 0x00000200 | 指示无论主机应用程序是否已启动,都将启动使用服务模板的功能。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 |
......
...@@ -26,8 +26,6 @@ Ability生命周期状态。 ...@@ -26,8 +26,6 @@ Ability生命周期状态。
| BACKGROUND | 3 | 表示Ability处于后台状态。 | | BACKGROUND | 3 | 表示Ability处于后台状态。 |
| DESTROY | 4 | 表示Ability处于已销毁状态。 | | DESTROY | 4 | 表示Ability处于已销毁状态。 |
## AbilityDelegatorRegistry.getAbilityDelegator ## AbilityDelegatorRegistry.getAbilityDelegator
getAbilityDelegator(): AbilityDelegator getAbilityDelegator(): AbilityDelegator
......
...@@ -29,7 +29,6 @@ Ability的状态信息。 ...@@ -29,7 +29,6 @@ Ability的状态信息。
| FOREGROUNDING | 11 | 表示ability为foregrounding状态。 | | FOREGROUNDING | 11 | 表示ability为foregrounding状态。 |
| BACKGROUNDING | 12 | 表示ability为backgrounding状态。 | | BACKGROUNDING | 12 | 表示ability为backgrounding状态。 |
## updateConfiguration ## updateConfiguration
updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
......
...@@ -6,12 +6,6 @@ AbilityRunningInfo模块提供对Ability运行的相关信息和状态进行设 ...@@ -6,12 +6,6 @@ AbilityRunningInfo模块提供对Ability运行的相关信息和状态进行设
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import abilitymanager from '@ohos.application.abilityManager';
```
## 使用说明 ## 使用说明
通过abilityManager中getAbilityRunningInfos方法获取。 通过abilityManager中getAbilityRunningInfos方法获取。
...@@ -36,21 +30,4 @@ abilitymanager.getAbilityRunningInfos((err,data) => { ...@@ -36,21 +30,4 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
| uid | number | 是 | 否 | 用户ID。 | | uid | number | 是 | 否 | 用户ID。 |
| processName | string | 是 | 否 | 进程名称。 | | processName | string | 是 | 否 | 进程名称。 |
| startTime | number | 是 | 否 | Ability启动时间。 | | startTime | number | 是 | 否 | Ability启动时间。 |
| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | 是 | 否 | Ability状态。 | | abilityState | [abilityManager.AbilityState](js-apis-abilityManager.md#abilityState) | 是 | 否 | Ability状态。 |
\ No newline at end of file
## abilityManager.AbilityState
Ability的状态信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
| 名称 | 值 | 说明 |
| -------- | -------- | -------- |
| INITIAL | 0 | 表示ability为initial状态。|
| FOREGROUND | 9 | 表示ability为foreground状态。 |
| BACKGROUND | 10 | 表示ability为background状态。 |
| FOREGROUNDING | 11 | 表示ability为foregrounding状态。 |
| BACKGROUNDING | 12 | 表示ability为backgrounding状态。 |
...@@ -9,12 +9,6 @@ AbilityStageContext提供允许访问特定于abilityStage的资源的能力, ...@@ -9,12 +9,6 @@ AbilityStageContext提供允许访问特定于abilityStage的资源的能力,
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```js
import AbilityStage from '@ohos.application.AbilityStage';
```
## 使用说明 ## 使用说明
通过AbilityStage实例来获取。 通过AbilityStage实例来获取。
......
# 动画 # 动画
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
>
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -22,7 +23,7 @@ createAnimator(options: AnimatorOptions): AnimatorResult ...@@ -22,7 +23,7 @@ createAnimator(options: AnimatorOptions): AnimatorResult
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | 是 | 定义动画选项,详细请参考AnimatorOptions。| | options | [AnimatorOptions](#animatoroptions) | 是 | 定义动画选项。|
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
...@@ -169,7 +170,7 @@ animator.reverse(); ...@@ -169,7 +170,7 @@ animator.reverse();
onframe: (progress: number) => void onframe: (progress: number) => void
回调时触发 接收到帧时回调
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
...@@ -187,7 +188,7 @@ animator.onframe(); ...@@ -187,7 +188,7 @@ animator.onframe();
onfinish: () => void onfinish: () => void
动画完成。 动画完成时回调
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
...@@ -200,7 +201,7 @@ animator.onfinish(); ...@@ -200,7 +201,7 @@ animator.onfinish();
oncancel: () => void oncancel: () => void
动画被取消。 动画被取消时回调
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
...@@ -213,6 +214,8 @@ animator.oncancel(); ...@@ -213,6 +214,8 @@ animator.oncancel();
onrepeat: () => void onrepeat: () => void
动画重复时回调。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
**示例:** **示例:**
...@@ -220,8 +223,6 @@ onrepeat: () => void ...@@ -220,8 +223,6 @@ onrepeat: () => void
animator.onrepeat(); animator.onrepeat();
``` ```
动画将重复。
## AnimatorOptions ## AnimatorOptions
定义动画选项。 定义动画选项。
...@@ -236,5 +237,5 @@ animator.onrepeat(); ...@@ -236,5 +237,5 @@ animator.onrepeat();
| fill | "none" \| "forwards" \| "backwards" \| "both" | 是 | 动画执行后是否恢复到初始状态,默认值为"none"。动画执行后,动画结束时的状态(在最后一个关键帧中定义)将保留。 | | fill | "none" \| "forwards" \| "backwards" \| "both" | 是 | 动画执行后是否恢复到初始状态,默认值为"none"。动画执行后,动画结束时的状态(在最后一个关键帧中定义)将保留。 |
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | 是 | 动画播放模式,默认值"normal"。| | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | 是 | 动画播放模式,默认值"normal"。|
| iterations | number | 是 | 动画播放次数,默认值1。设置为0时不播放,设置为-1时无限次播放。 | | iterations | number | 是 | 动画播放次数,默认值1。设置为0时不播放,设置为-1时无限次播放。 |
| begin | number | 是 | 动画插值起点,不设置时默认为0。 | | begin | number | 是 | 动画插值起点,默认为0。 |
| end | number | 是 | 动画插值终点,不设置时默认为1。 | | end | number | 是 | 动画插值终点,默认为1。 |
# EnvironmentCallback
EnvironmentCallback模块提供应用上下文ApplicationContext对系统环境变化监听回调的能力,包括onConfigurationUpdated方法。
> **说明:**
>
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。
## 导入模块
```js
import EnvironmentCallback from "@ohos.application.EnvironmentCallback";
```
## EnvironmentCallback.onConfigurationUpdated
onConfigurationUpdated(config: Configuration): void;
注册系统环境变化的监听后,在系统环境变化时触发回调。
**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-configuration.md) | 是 | 变化后的Configuration对象。 |
**示例:**
```js
import AbilityStage from "@ohos.application.AbilityStage";
var callbackId;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
}
// 1.获取applicationContext
let applicationContext = globalThis.applicationContext;
// 2.通过applicationContext注册监听应用内生命周期
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId));
}
onDestroy() {
let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error));
});
}
}
```
\ No newline at end of file
# MissionSnapshot # MissionSnapshot
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** MissionSnapshot模块提供设置与任务对应的任务快照的任务元素名称的能力。
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
任务对应的任务快照。
## 导入模块
``` > **说明:**
import missionManager from '@ohos.application.missionManager' >
``` > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口均为系统接口,三方应用不支持调用
## 使用说明 ## 使用说明
使用前需要提前引入对应模块 通过missionManager中的getMissionSnapShot来获取
``` ```js
import ElementName from '@ohos.bundle'; import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getMissionSnapShot("", id, (error, snapshot) => {
console.log("getMissionSnapShot is called, error.code = " + error.code);
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
``` ```
## MissionSnapshot ## MissionSnapshot
表示任务对应的任务快照的枚举。 表示任务对应的任务快照的枚举。
| 名称 | 参数类型 | 可读 | 可写 | 说明 | **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | 是 | 是 | 表示Ability任务元素名称。 | | ability | ElementName | 是 | 是 | 表示Ability任务元素名称。 |
| snapshot | [image.PixelMap](js-apis-image.md) | 是 | 是 | 表示任务快照。 | | snapshot | [image.PixelMap](js-apis-image.md) | 是 | 是 | 表示任务快照。 |
...@@ -25,6 +25,6 @@ import Want from '@ohos.application.Want'; ...@@ -25,6 +25,6 @@ import Want from '@ohos.application.Want';
| type | 只读 | string | 否 | 表示MIME type类型描述,比如:"text/plain" 、 "image/*"等。 | | type | 只读 | string | 否 | 表示MIME type类型描述,比如:"text/plain" 、 "image/*"等。 |
| flags | 只读 | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-featureAbility.md#flags说明)。 | | flags | 只读 | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-featureAbility.md#flags说明)。 |
| action | 只读 | string | 否 | 表示action选项描述。 | | action | 只读 | string | 否 | 表示action选项描述。 |
| parameters | 只读 | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.pacallerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示发起方的uid。[Bundle](js-apis-Bundle.js)模块中userId参数,可用于获取应用信息、包信息等,具体参考:[Bundle](js-apis-Bundle.js)。 | | parameters | 只读 | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示发起方的uid。[Bundle](js-apis-Bundle.js)模块中userId参数,可用于获取应用信息、包信息等,具体参考:[Bundle](js-apis-Bundle.js)。 |
| entities | 只读 | Array\<string> | 否 | 表示entities相关描述。 | | entities | 只读 | Array\<string> | 否 | 表示entities相关描述。 |
| moduleName<sup>9+</sup> | 只读 | string | 否 | 表示待启动的Ability所属的模块(module)。同一应用的不同hap的组件可能重名,仅通过BundleName和AbilityName无法区分时,可以通过设置moduleName加以区分,以匹配到指定的Ability。 | | | moduleName<sup>9+</sup> | 只读 | string | 否 | 表示待启动的Ability所属的模块(module)。同一应用的不同hap的组件可能重名,仅通过BundleName和AbilityName无法区分时,可以通过设置moduleName加以区分,以匹配到指定的Ability。 | |
...@@ -29,8 +29,6 @@ import Ability from '@ohos.application.Ability'; ...@@ -29,8 +29,6 @@ import Ability from '@ohos.application.Ability';
| lastRequestWant | [Want](js-apis-application-Want.md) | 是 | 否 | Ability最后请求时的参数。| | lastRequestWant | [Want](js-apis-application-Want.md) | 是 | 否 | Ability最后请求时的参数。|
| callee | [Callee](#callee) | 是 | 否 | 调用Stub(桩)服务对象。| | callee | [Callee](#callee) | 是 | 否 | 调用Stub(桩)服务对象。|
## Ability.onCreate ## Ability.onCreate
onCreate(want: Want, param: AbilityConstant.LaunchParam): void; onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
......
...@@ -6,10 +6,16 @@ AbilityDelegator提供添加用于监视指定能力的生命周期状态更改 ...@@ -6,10 +6,16 @@ AbilityDelegator提供添加用于监视指定能力的生命周期状态更改
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 使用说明
通过AbilityDelegatorRegistry中getAbilityDelegator方法获取。
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
``` ```
## AbilityDelegator ## AbilityDelegator
......
...@@ -6,10 +6,14 @@ AbilityDelegatorArgs模块提供在应用程序启动期间,用于存储已注 ...@@ -6,10 +6,14 @@ AbilityDelegatorArgs模块提供在应用程序启动期间,用于存储已注
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 使用说明
通过AbilityDelegatorRegistry中getArguments方法获取。
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var args = AbilityDelegatorRegistry.getArguments();
``` ```
## AbilityDelegatorArgs ## AbilityDelegatorArgs
......
...@@ -6,10 +6,27 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方 ...@@ -6,10 +6,27 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方
> >
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 使用说明
通过abilityDelegator中的addAbilityMonitor来设置。
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
abilityName: "abilityname",
onAbilityCreate: onAbilityCreateCallback
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
console.info("addAbilityMonitor callback");
});
``` ```
## AbilityMonitor ## AbilityMonitor
......
...@@ -7,12 +7,6 @@ ApplicationContext模块提供开发者应用级别的的上下文的能力, ...@@ -7,12 +7,6 @@ ApplicationContext模块提供开发者应用级别的的上下文的能力,
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```
import Ability from '@ohos.application.Ability';
```
## 使用说明 ## 使用说明
在使用ApplicationContext的功能前,需要通过context的实例获取。 在使用ApplicationContext的功能前,需要通过context的实例获取。
...@@ -34,20 +28,20 @@ registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number** ...@@ -34,20 +28,20 @@ registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------------------ | -------- | ---- | ------------------------------ | | ------------------------ | -------- | ---- | ------------------------------ |
| [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | 是 | 回调方法,返回注册监听事件的id | | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | 是 | 回调方法,返回注册监听事件的ID。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------ | ------------------------------ | | ------ | ------------------------------ |
| number | 返回的此次注册监听生命周期的id(每次注册该id会自增+1,当超过监听上限数量2^63-1时,返回-1)| | number | 返回的此次注册监听生命周期的ID(每次注册该ID会自增+1,当超过监听上限数量2^63-1时,返回-1)。|
**示例:** **示例:**
```js ```js
import AbilityStage from "@ohos.application.AbilityStage"; import AbilityStage from "@ohos.application.AbilityStage";
var lifecycleid; var lifecycleId;
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
...@@ -78,18 +72,19 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -78,18 +72,19 @@ export default class MyAbilityStage extends AbilityStage {
// 1.通过context属性获取applicationContext // 1.通过context属性获取applicationContext
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// 2.通过applicationContext注册监听应用内生命周期 // 2.通过applicationContext注册监听应用内生命周期
lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId));
} }
onDestroy() { onDestroy() {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
}); });
} }
} }
``` ```
## ApplicationContext.unregisterAbilityLifecycleCallback ## ApplicationContext.unregisterAbilityLifecycleCallback
unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
...@@ -102,16 +97,92 @@ unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallb ...@@ -102,16 +97,92 @@ unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallb
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------- | -------- | ---- | -------------------------- | | ------------- | -------- | ---- | -------------------------- |
| callbackId | number | 是 | 注册监听应用内生命周期的id | | callbackId | number | 是 | 注册监听应用内生命周期的ID。 |
| AsyncCallback | callback | 是 | 回调方法 | | AsyncCallback | callback | 是 | 回调方法 |
**示例:** **示例:**
```js ```js
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
let lifecycleid=1 let lifecycleId = 1;
console.log("stage applicationContext: " + JSON.stringify(applicationContext)); console.log("stage applicationContext: " + JSON.stringify(applicationContext));
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
}); });
``` ```
## ApplicationContext.registerEnvironmentCallback
registerEnvironmentCallback(callback: EnvironmentCallback): **number**;
注册对系统环境变化的监听。使用callback异步回调。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------------------ | -------- | ---- | ------------------------------ |
| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | 是 | 回调方法,返回注册监听事件的ID。 |
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------------ |
| number | 返回的此次注册监听系统环境变化的ID(每次注册该ID会自增+1,当超过监听上限数量2^63-1时,返回-1)。|
**示例:**
```js
import AbilityStage from "@ohos.application.AbilityStage";
var callbackId;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
}
// 1.获取applicationContext
let applicationContext = globalThis.applicationContext;
// 2.通过applicationContext注册监听应用内生命周期
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId));
}
onDestroy() {
let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error));
});
}
}
```
## ApplicationContext.unregisterEnvironmentCallback
unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
取消对系统环境变化的监听。使用callback异步回调。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | 是 | 注册监听系统环境变化的ID。 |
| AsyncCallback | callback | 是 | 回调方法。 |
**示例:**
```js
let applicationContext = this.context.getApplicationContext();
let callbackId = 1;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error));
});
```
...@@ -9,15 +9,20 @@ Context模块提供开发者运行代码的上下文环境的能力,包括查 ...@@ -9,15 +9,20 @@ Context模块提供开发者运行代码的上下文环境的能力,包括查
提供开发者运行代码的上下文环境,包括应用信息、ResourceManager等信息。 提供开发者运行代码的上下文环境,包括应用信息、ResourceManager等信息。
## 导入模块
```
import AbilityContext from '@ohos.application.Ability';
```
## 使用说明 ## 使用说明
通过AbilityContext等继承实现。 通过AbilityContext等继承实现。
```js
import AbilityContext from '@ohos.application.Ability'
class MainAbility extends AbilityContext {
onWindowStageCreate(windowStage) {
let test = "com.example.test";
let context = this.context.createBundleContext(test);
}
}
```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
...@@ -30,12 +35,11 @@ import AbilityContext from '@ohos.application.Ability'; ...@@ -30,12 +35,11 @@ import AbilityContext from '@ohos.application.Ability';
| tempDir | string | 是 | 否 | 应用的临时文件路径。 | | tempDir | string | 是 | 否 | 应用的临时文件路径。 |
| filesDir | string | 是 | 否 | 应用在内部存储上的文件路径。 | | filesDir | string | 是 | 否 | 应用在内部存储上的文件路径。 |
| databaseDir | string | 是 | 否 | 获取本地数据存储路径。 | | databaseDir | string | 是 | 否 | 获取本地数据存储路径。 |
| storageDir | string | 是 | 否 | 获取轻量级数据存储路径。 |
| bundleCodeDir | string | 是 | 否 | 应用安装路径。 | | bundleCodeDir | string | 是 | 否 | 应用安装路径。 |
| distributedFilesDir | string | 是 | 否 | 应用的分布式文件路径。 | | distributedFilesDir | string | 是 | 否 | 应用的分布式文件路径。 |
| eventHub | [EventHub](js-apis-eventhub.md) | 是 | 否 | 事件中心信息。| | eventHub | [EventHub](js-apis-eventhub.md) | 是 | 否 | 事件中心信息。|
| area | [AreaMode](#areamode) | 是 | 是 | 文件分区。| | area | [AreaMode](#areamode) | 是 | 是 | 文件分区。|
| preferencesDir | string | 是 | 是 | 指示应用程序首选项目录。|
## Context.createBundleContext ## Context.createBundleContext
......
# MissionInfo
MissionInfo模块提供对与Ability相对应的任务信息进行设置和查询的能力。
> **说明:**
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import MissionInfo from '@ohos.application.missionInfo'
```
## MissionInfo
表示Ability对应任务信息的枚举。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| missionId | number | 是 | 是 | 表示任务ID。|
| runningState | number | 是 | 是 | 表示运行状态。 |
| lockedState | boolean | 是 | 是 | 表示锁定状态。 |
| timestamp | string | 是 | 是 | 表示任务的最近创建或更新时间。 |
| want | [Want](js-apis-application-Want.md) | 是 | 是 | 表示任务的Want信息。 |
| label | string | 是 | 是 | 表示任务的标签。 |
| iconPath | string | 是 | 是 | 表示任务的图标路径。 |
| continuable | boolean | 是 | 是 | 表示任务是否可以继续。 |
...@@ -6,16 +6,28 @@ ShellCmdResult模块提供Shell命令执行结果的能力。 ...@@ -6,16 +6,28 @@ ShellCmdResult模块提供Shell命令执行结果的能力。
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 使用说明
通过abilityDelegator中的executeShellCommand方法来获取。
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var abilityDelegator;
var cmd = "cmd";
var timeout = 100;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => {
console.info("executeShellCommand promise");
});
``` ```
## ShellCmdResult ## ShellCmdResult
Shell命令执行结果 Shell命令执行结果
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | | --------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| stdResult | string | 是 | 是 | 标准输出内容<br/>**系统能力:** SystemCapability.Ability.AbilityRuntime.Core | | stdResult | string | 是 | 是 | 标准输出内容<br/>**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
......
...@@ -6,8 +6,6 @@ appManager模块提供服务功能的能力,包括查询当前是否处于稳 ...@@ -6,8 +6,6 @@ appManager模块提供服务功能的能力,包括查询当前是否处于稳
> >
> 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
App管理。
## 导入模块 ## 导入模块
```js ```js
...@@ -208,6 +206,388 @@ getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): vo ...@@ -208,6 +206,388 @@ getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): vo
}) })
``` ```
## appManager.registerApplicationStateObserver<sup>8+</sup>
registerApplicationStateObserver(observer: ApplicationStateObserver): number;
注册应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| observer | ApplicationStateObserver | 否 | 返回观察者的数字代码。 |
**示例:**
```js
var applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log('------------ onForegroundApplicationChanged -----------', appStateData);
},
onAbilityStateChanged(abilityStateData) {
console.log('------------ onAbilityStateChanged -----------', abilityStateData);
},
onProcessCreated(processData) {
console.log('------------ onProcessCreated -----------', processData);
},
onProcessDied(processData) {
console.log('------------ onProcessDied -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
```
## appManager.unregisterApplicationStateObserver<sup>8+</sup>
unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\<void>): void;
取消注册应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| observerId | number | 否 | 表示观察者的编号代码。 |
| callback | AsyncCallback\<void> | 否 | 表示指定的回调方法。 |
**示例:**
```js
var observerId = 100;
function unregisterApplicationStateObserverCallback(err) {
if (err) {
console.log('------------ unregisterApplicationStateObserverCallback ------------', err);
}
}
app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback);
```
## appManager.unregisterApplicationStateObserver<sup>8+</sup>
unregisterApplicationStateObserver(observerId: number): Promise\<void>;
取消注册应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| observerId | number | 否 | 表示观察者的编号代码。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
**示例:**
```js
var observerId = 100;
app.unregisterApplicationStateObserver(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err);
})
```
## appManager.getForegroundApplications<sup>8+</sup>
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
获取前台进程的应用程序。
**需要权限**:ohos.permission.GET_RUNNING_INFO
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<AppStateData>> | 否 | 表示应用的状态数据。 |
**示例:**
```js
function getForegroundApplicationsCallback(err, data) {
if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err);
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data)
}
}
app.getForegroundApplications(getForegroundApplicationsCallback);
```
## appManager.getForegroundApplications<sup>8+</sup>
getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>;
获取前台进程的应用程序。
**需要权限**:ohos.permission.GET_RUNNING_INFO
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<Array\<ProcessRunningInfo>> | 返回进程运行信息的数组。 |
**示例:**
```js
app.getForegroundApplications()
.then((data) => {
console.log('--------- getForegroundApplications success -------', data);
})
.catch((err) => {
console.log('--------- getForegroundApplications fail -------', err);
})
```
## appManager.killProcessWithAccount<sup>8+</sup>
killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
切断account进程(Promise形式)。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用包名。 |
| accountId | number | 是 | account的Id。 |
**示例:**
```js
var bundleName = 'bundleName';
var accountId = 0;
app.killProcessWithAccount(bundleName, accountId)
.then((data) => {
console.log('------------ killProcessWithAccount success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessWithAccount fail ------------', err);
})
```
## appManager.killProcessWithAccount<sup>8+</sup>
killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\<void\>): void
切断account进程(callback形式)。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用包名。 |
| accountId | number | 是 | account的Id。 |
| callback | AsyncCallback\<void\> | 是 | 切断account进程的回调函数。 |
**示例:**
```js
var bundleName = 'bundleName';
var accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err) {
console.log('------------- killProcessWithAccountCallback fail, err: --------------', err);
} else {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
}
}
app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
```
## appManager.killProcessesByBundleName<sup>8+</sup>
killProcessesByBundleName(bundleName: string, callback: AsyncCallback\<void>);
通过包名终止进程。
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 否 | 表示包名。 |
| callback | AsyncCallback\<void> | 否 | 表示指定的回调方法。 |
**示例:**
```js
var bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err) {
console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
} else {
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
}
}
app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
```
## appManager.killProcessesByBundleName<sup>8+</sup>
killProcessesByBundleName(bundleName: string): Promise\<void>;
通过包名终止进程。
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 否 | 表示包名。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
**示例:**
```js
var bundleName = 'bundleName';
app.killProcessesByBundleName(bundleName)
.then((data) => {
console.log('------------ killProcessesByBundleName success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessesByBundleName fail ------------', err);
})
```
## appManager.clearUpApplicationData<sup>8+</sup>
clearUpApplicationData(bundleName: string, callback: AsyncCallback<void>);
通过包名清除应用数据。
**需要权限**:ohos.permission.CLEAN_APPLICATION_DATA
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 否 | 表示包名。 |
| callback | AsyncCallback\<void> | 否 | 表示指定的回调方法。 |
**示例:**
```js
var bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err) {
console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err);
} else {
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
}
}
app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
```
## appManager.clearUpApplicationData<sup>8+</sup>
clearUpApplicationData(bundleName: string): Promise<void>;
通过包名清除应用数据。
**需要权限**:ohos.permission.CLEAN_APPLICATION_DATA
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 否 | 表示包名。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
**示例:**
```js
var bundleName = 'bundleName';
app.clearUpApplicationData(bundleName)
.then((data) => {
console.log('------------ clearUpApplicationData success ------------', data);
})
.catch((err) => {
console.log('------------ clearUpApplicationData fail ------------', err);
})
```
## ProcessRunningInfo ## ProcessRunningInfo
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -13,26 +13,28 @@ ...@@ -13,26 +13,28 @@
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | 是 | 否 | 应用程序的名称 | | name | string | 是 | 否 | 应用程序的名称。 |
| description | string | 是 | 否 | 应用程序的描述 | | description | string | 是 | 否 | 应用程序的描述。 |
| descriptionId | number | 是 | 否 | 应用程序的描述id | | descriptionId | number | 是 | 否 | 应用程序的描述id。 |
| systemApp | boolean | 是 | 否 | 判断是否为系统应用程序,默认为false | | systemApp | boolean | 是 | 否 | 判断是否为系统应用程序,默认为false。 |
| enabled | boolean | 是 | 否 | 判断应用程序是否可以使用,默认为true | | enabled | boolean | 是 | 否 | 判断应用程序是否可以使用,默认为true。 |
| label | string | 是 | 否 | 应用程序的标签 | | label | string | 是 | 否 | 应用程序的标签。 |
| labelId | string | 是 | 否 | 应用程序的标签id | | labelId | string | 是 | 否 | 应用程序的标签id。 |
| icon | string | 是 | 否 | 应用程序的图标 | | icon | string | 是 | 否 | 应用程序的图标。 |
| iconId | string | 是 | 否 | 应用程序的图标id | | iconId | string | 是 | 否 | 应用程序的图标id。 |
| process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称 | | process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称。 |
| supportedModes | number | 是 | 否 | 应用程序支持的运行模式 | | supportedModes | number | 是 | 否 | 应用程序支持的运行模式。 |
| moduleSourceDirs | Array\<string> | 是 | 否 | 应用程序的资源存放的相对路径 | | moduleSourceDirs | Array\<string> | 是 | 否 | 应用程序的资源存放的相对路径。 |
| permissions | Array\<string> | 是 | 否 | 访问应用程序所需的权限 | | permissions | Array\<string> | 是 | 否 | 访问应用程序所需的权限。 |
| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | 是 | 否 | 应用程序的模块信息 | | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | 是 | 否 | 应用程序的模块信息。 |
| entryDir | string | 是 | 否 | 应用程序的文件保存路径 | | entryDir | string | 是 | 否 | 应用程序的文件保存路径。 |
| codePath<sup>8+</sup> | string | 是 | 否 | 应用程序的安装目录 | | codePath<sup>8+</sup> | string | 是 | 否 | 应用程序的安装目录。 |
| metaData<sup>8+</sup> | Map\<string, Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)>> | 是 | 否 | 应用程序的自定义元信息 | | metaData<sup>8+</sup> | Map\<string, Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)>> | 是 | 否 | 应用程序的自定义元信息。 |
| metadata<sup>9+</sup> | Map\<string, Array\<[Metadata](js-apis-bundle-Metadata.md)>> | 是 | 否 | 应用程序的元信息 | | metadata<sup>9+</sup> | Map\<string, Array\<[Metadata](js-apis-bundle-Metadata.md)>> | 是 | 否 | 应用程序的元信息。 |
| removable<sup>8+</sup> | boolean | 是 | 否 | 应用程序是否可以被移除 | | removable<sup>8+</sup> | boolean | 是 | 否 | 应用程序是否可以被移除。 |
| accessTokenId<sup>8+</sup> | number | 是 | 否 | 应用程序的accessTokenId | | accessTokenId<sup>8+</sup> | number | 是 | 否 | 应用程序的accessTokenId。 |
| uid<sup>8+</sup> | number | 是 | 否 | 应用程序的uid | | uid<sup>8+</sup> | number | 是 | 否 | 应用程序的uid。 |
| entityType<sup>8+</sup> | string | 是 | 否 | 应用程序的实体类型 | | entityType<sup>8+</sup> | string | 是 | 否 | 应用程序的实体类型。 |
| fingerprint<sup>9+</sup> | string | 是 | 否 | 应用程序的签名证书指纹信息,即开发者申请的签名证书的sha256值 | | fingerprint<sup>9+</sup> | string | 是 | 否 | 应用程序的签名证书指纹信息,即开发者申请的签名证书的sha256值。 |
| appDistributionType<sup>9+</sup> | string | 是 | 否 | 应用程序签名证书的分发类型,分为:app_gallery、enterprise、os_integration和crowdtesting。 |
| appProvisionType<sup>9+</sup> | string | 是 | 否 | 应用程序签名证书文件的类型,分为debug和release两种类型。|
# 相机管理 # 相机管理
> **说明:** > **说明:**
>
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
...@@ -1034,7 +1035,7 @@ on(type: 'error', callback: ErrorCallback<CameraInputError\>): void ...@@ -1034,7 +1035,7 @@ on(type: 'error', callback: ErrorCallback<CameraInputError\>): void
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| :------- | :------------------------------- | :--- | :----------------------------------------------- | | :------- | :------------------------------- | :--- | :----------------------------------------------- |
| type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 | | type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 |
| callback | ErrorCallback<CameraInputError\> | 是 | 回调函数,用于获取结果。 | | callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
...@@ -1044,6 +1045,26 @@ cameraInput.on('error', (cameraInputError) => { ...@@ -1044,6 +1045,26 @@ cameraInput.on('error', (cameraInputError) => {
}) })
``` ```
## CameraInputErrorCode
枚举,CameraInput的错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ------------- | ---- | ---------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
## CameraInputError
CameraInput错误对象。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 说明 |
| ---- | ------------------------------------------- | -------------------------- |
| code | [CameraInputErrorCode](#camerainputerrorcode) | CameraInput中的错误码。 |
## FlashMode ## FlashMode
...@@ -2068,7 +2089,7 @@ previewOutput.on('error', (previewOutputError) => { ...@@ -2068,7 +2089,7 @@ previewOutput.on('error', (previewOutputError) => {
| 名称 | 类型 | 说明 | | 名称 | 类型 | 说明 |
| ---- | ------------------------------------------------- | ---------------------- | | ---- | ------------------------------------------------- | ---------------------- |
| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOut中的错误码。 | | code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOutput中的错误码。 |
## camera.createPhotoOutput ## camera.createPhotoOutput
......
...@@ -16,20 +16,21 @@ import CommonEvent from '@ohos.commonEvent'; ...@@ -16,20 +16,21 @@ import CommonEvent from '@ohos.commonEvent';
CommonEvent模块支持的事件类型。名称指的是系统公共事件宏;值指的是系统公共事件。 CommonEvent模块支持的事件类型。名称指的是系统公共事件宏;值指的是系统公共事件。
**系统能力:** SystemCapability.Notification.CommonEvent
| 名称 | 值 | 订阅者所需权限 | 说明 | | 名称 | 值 | 订阅者所需权限 | 说明 |
| ------------ | ------------------ | ---------------------- | -------------------- | | ------------ | ------------------ | ---------------------- | -------------------- |
| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 指示用户已完成引导并加载系统的公共事件的操作。 | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 指示用户已完成引导并加载系统的公共事件的操作。 |
| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导,系统已加载,但屏幕仍锁定的公共事件的操作。 | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导,系统已加载,但屏幕仍锁定的公共事件的操作。 |
| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | 无 | 指示设备正在关闭并将继续最终关闭的公共事件的操作。 | | COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | 无 | 指示设备正在关闭并将继续最终关闭的公共事件的操作。 |
| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | 无 | 表示电池充电状态、电平和其他信息发生变化的公共事件的动作。 | | COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | 无 | 表示电池充电状态、电平和其他信息发生变化的公共事件的动作。 |
| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | 无 | | COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | 无 | 表示电池电量低的普通事件的动作。 |
表示电池电量低的普通事件的动作。 |
| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | 无 | 表示电池退出低电平状态的公共事件的动作。 | | COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | 无 | 表示电池退出低电平状态的公共事件的动作。 |
| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | 无 | 设备连接到外部电源的公共事件的动作。 | | COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | 无 | 设备连接到外部电源的公共事件的动作。 |
| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | 无 | 设备与外部电源断开的公共事件的动作。 | | COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | 无 | 设备与外部电源断开的公共事件的动作。 |
| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | 无 | 指示设备屏幕关闭且设备处于睡眠状态的普通事件的动作。 | | COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | 无 | 指示设备屏幕关闭且设备处于睡眠状态的普通事件的动作。 |
| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | 无 | 指示设备屏幕打开且设备处于交互状态的公共事件的操作。 | | COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | 无 | 指示设备屏幕打开且设备处于交互状态的公共事件的操作。 |
| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | 无 | 指示设备热状态的公共事件的动作。 | | COMMON_EVENT_THERMAL_LEVEL_CHANGED<sup>8+<sup> | usual.event.THERMAL_LEVEL_CHANGED | 无 | 指示设备热状态的公共事件的动作。 |
| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | 无 | 用户解锁设备的公共事件的动作。 | | COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | 无 | 用户解锁设备的公共事件的动作。 |
| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | 无 | 表示系统时间更改的公共事件的动作。 | | COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | 无 | 表示系统时间更改的公共事件的动作。 |
| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | 无 | 设置系统时间的公共事件的动作。 | | COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | 无 | 设置系统时间的公共事件的动作。 |
...@@ -158,16 +159,16 @@ CommonEvent模块支持的事件类型。名称指的是系统公共事件宏; ...@@ -158,16 +159,16 @@ CommonEvent模块支持的事件类型。名称指的是系统公共事件宏;
| 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 |
| 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为插卡情况下无法挂载时发送此公共事件。 |
| 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 用户已表示希望删除外部存储介质时发送此公共事件。 |
| COMMON_EVENT_VOLUME_REMOVED | 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为移除时发送此公共事件。 |
| COMMON_EVENT_VOLUME_UNMOUNTED | 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为卸载时发送此公共事件。 |
| COMMON_EVENT_VOLUME_MOUNTED | 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载时发送此公共事件。 |
| COMMON_EVENT_VOLUME_BAD_REMOVAL | 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 |
| COMMON_EVENT_VOLUME_EJECT | 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.WRITE_USER_STORAGE 或 ohos.permission.READ_USER_STORAGE | 用户已表示希望删除外部存储介质时发送此公共事件。 |
| 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已准备好的公共事件的动作。 |
| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | 无 | 表示设备飞行模式已更改的公共事件的动作。 | | COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | 无 | 表示设备飞行模式已更改的公共事件的动作。 |
| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | 表示分屏的公共事件的动作。 | | COMMON_EVENT_SPLIT_SCREEN<sup>8+<sup> | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | 表示分屏的公共事件的动作。 |
## CommonEvent.publish ## CommonEvent.publish
...@@ -178,8 +179,6 @@ publish(event: string, callback: AsyncCallback\<void>): void ...@@ -178,8 +179,6 @@ publish(event: string, callback: AsyncCallback\<void>): void
**系统能力:** SystemCapability.Notification.CommonEvent **系统能力:** SystemCapability.Notification.CommonEvent
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 名称 | 读写属性 | 类型 | 必填 | 描述 | | 名称 | 读写属性 | 类型 | 必填 | 描述 |
...@@ -213,8 +212,6 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\ ...@@ -213,8 +212,6 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\
**系统能力:** SystemCapability.Notification.CommonEvent **系统能力:** SystemCapability.Notification.CommonEvent
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 名称 | 读写属性 | 类型 | 必填 | 描述 | | 名称 | 读写属性 | 类型 | 必填 | 描述 |
......
# ContinuationExtraParams
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import continuationManager from "@ohos.continuation.continuationManager"
```
## ContinuationExtraParams
表示流转管理入口中互联面板所需的过滤参数。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.DistributedAbilityManager
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| deviceType | Array\<string> | 是 | 是 | 表示设备类型。|
| targetBundle | string | 是 | 是 | 表示目标包名。 |
| description | string | 是 | 是 | 表示设备过滤的描述。 |
| filter | any | 是 | 是 | 表示设备过滤的参数。 |
| continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | 是 | 是 | 表示协同的模式。 |
| authInfo | { [key: string]: any } | 是 | 是 | 表示认证的信息。 |
\ No newline at end of file
# continuationManager
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
continuationManager模块提供了流转/协同入口管理服务能力,包括连接/取消流转管理服务,注册/解注册设备连接变化监听,拉起互联面板,更新连接状态。
## 导入模块
```js
import continuationManager from '@ohos.continuation.continuationManager'
```
## continuationManager.register
register(callback: AsyncCallback\<number>): void;
注册流转管理服务,并获取对应的注册token,无过滤条件,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<number> | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 |
**示例:**
```js
let token = -1;
continuationManager.register((err, data) => {
if (err.code != 0) {
console.error('register failed, cause: ' + JSON.stringify(err));
return;
}
console.info('register finished, ' + JSON.stringify(data));
token = data;
});
```
## continuationManager.register
register(options: ContinuationExtraParams, callback: AsyncCallback\<number>): void;
连接流转管理服务,并获取对应的注册token,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 |
| callback | AsyncCallback\<number> | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 |
**示例:**
```js
let token = -1;
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.register(continuationExtraParams, (err, data) => {
if (err.code != 0) {
console.error('register failed, cause: ' + JSON.stringify(err));
return;
}
console.info('register finished, ' + JSON.stringify(data));
token = data;
});
```
## continuationManager.register
register(options?: ContinuationExtraParams): Promise\<number>;
连接流转管理服务,并获取对应的注册token,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 否 | 过滤可选择设备列表的额外参数,该参数可缺省|
**示例:**
```js
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.register(continuationExtraParams)
.then((data) => {
console.info('register finished, ' + JSON.stringify(data));
token = data;
})
.catch((err) => {
console.error('register failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.on("deviceConnect")<sup>(deprecated)</sup>
> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceconnect)替代。
on(type: "deviceConnect", callback: Callback\<ContinuationResult>): void;
异步方法,监听设备连接状态,使用Callback形式返回连接的设备信息。
## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup>
> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondevicedisconnect)替代。
on(type: "deviceDisconnect", callback: Callback\<string>): void;
异步方法,监听设备断开状态,使用Callback形式返回断开的设备信息。
## continuationManager.off("deviceConnect")<sup>(deprecated)</sup>
> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceconnect)替代。
off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void;
异步方法,取消监听设备连接状态,使用Callback形式返回连接的设备信息。
## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup>
> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdevicedisconnect)替代。
off(type: "deviceDisconnect", callback?: Callback\<string>): void;
异步方法,取消监听设备断开状态,使用Callback形式返回连接的设备信息。
## continuationManager.on("deviceConnect")
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
异步方法,监听设备连接状态,使用Callback形式返回连接的设备信息。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 监听的事件类型,固定值"deviceConnect"。 |
| token | number | 是 | 注册后的token。 |
| callback | Callback\<Array\<[ContinuationResult](js-apis-continuation-continuationResult.md)>> | 是 | 当用户从互联面板中选择设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 |
**示例:**
```js
continuationManager.on("deviceConnect", token, (data) => {
console.info('onDeviceConnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id));
console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type));
console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name));
}
});
```
## continuationManager.on("deviceDisconnect")
on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void;
异步方法,监听设备断开状态,使用Callback形式返回断开的设备信息。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 监听的事件类型,固定值"deviceDisconnect"。 |
| token | number | 是 | 注册后的token。 |
| callback | Callback\<Array\<string>> | 是 | 当用户从互联面板中断开设备时调用,返回设备ID供开发者使用。 |
**示例:**
```js
continuationManager.on("deviceDisconnect", token, (data) => {
console.info('onDeviceDisconnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i]));
}
console.info('onDeviceDisconnect finished.');
});
```
## continuationManager.off("deviceConnect")
off(type: "deviceConnect", token: number): void;
取消监听设备连接状态。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消监听的事件类型,固定值"deviceConnect"。 |
| token | number | 是 | 注册后的token。 |
**示例:**
```js
continuationManager.off("deviceConnect", token);
```
## continuationManager.off("deviceDisconnect")
off(type: "deviceDisconnect", token: number): void;
取消监听设备断开状态。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消监听的事件类型,固定值"deviceDisconnect"。 |
| token | number | 是 | 注册后的token。 |
**示例:**
```js
continuationManager.off("deviceDisconnect", token);
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, callback: AsyncCallback\<void>): void;
拉起互联面板,可显示组网内可选择设备列表信息,无过滤条件,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| callback | AsyncCallback\<void> | 是 | AsyncCallback形式返回接口调用结果。 |
**示例:**
```js
continuationManager.startDeviceManager(token, (err, data) => {
if (err.code != 0) {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
return;
}
console.info('startDeviceManager finished, ' + JSON.stringify(data));
});
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\<void>): void;
拉起互联面板,可显示组网内可选择设备列表信息,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 |
| callback | AsyncCallback\<void> | 是 | AsyncCallback形式返回接口调用结果。 |
**示例:**
```js
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.startDeviceManager(token, continuationExtraParams, (err, data) => {
if (err.code != 0) {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
return;
}
console.info('startDeviceManager finished, ' + JSON.stringify(data));
});
```
## continuationManager.startDeviceManager
startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\<void>;
拉起互联面板,可显示组网内可选择设备列表信息,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 否 | 过滤可选择设备列表的额外参数,该参数可缺省|
**示例:**
```js
let continuationExtraParams = {
deviceType: ["00E"]
};
continuationManager.startDeviceManager(token, continuationExtraParams)
.then((data) => {
console.info('startDeviceManager finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.updateConnectStatus
updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\<void>): void;
通知互联面板,更新当前的连接状态,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| deviceId | string | 是 | 设备ID。 |
| status | [DeviceConnectState](#deviceconnectstate) | 是 | 设备连接状态。 |
| callback | AsyncCallback\<void> | 是 | AsyncCallback形式返回接口调用结果。 |
**示例:**
```js
let deviceId: string = "test deviceId";
continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED, (err, data) => {
if (err.code != 0) {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
return;
}
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
});
```
## continuationManager.updateConnectStatus
updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\<void>;
通知互联面板,更新当前的连接状态,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| deviceId | string | 是 | 设备ID。 |
| status | [DeviceConnectState](#deviceconnectstate) | 是 | 设备连接状态。 |
**示例:**
```js
let deviceId: string = "test deviceId";
continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED)
.then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
});
```
## continuationManager.unregister
unregister(token: number, callback: AsyncCallback\<void>): void;
解注册流转管理服务,传入注册时获取的token进行解注册,使用AsyncCallback方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
| callback | AsyncCallback\<void> | 是 | AsyncCallback形式返回接口调用结果。 |
**示例:**
```js
continuationManager.unregister(token, (err, data) => {
if (err.code != 0) {
console.error('unregister failed, cause: ' + JSON.stringify(err));
return;
}
console.info('unregister finished, ' + JSON.stringify(data));
});
```
## continuationManager.unregister
unregister(token: number): Promise\<void>;
解注册流转管理服务,传入注册时获取的token进行解注册,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | number | 是 | 注册后的token。 |
**示例:**
```js
continuationManager.unregister(token)
.then((data) => {
console.info('unregister finished, ' + JSON.stringify(data));
})
.catch((err) => {
console.error('unregister failed, cause: ' + JSON.stringify(err));
});
```
## DeviceConnectState
设备连接状态。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 值 | 说明 |
| -------- | -------- | -------- | -------- |
| IDLE | number | 0 | 设备连接初始状态。 |
| CONNECTING | number | 1 | 设备连接中状态。 |
| CONNECTED | number | 2 | 设备已连接状态。 |
| DISCONNECTING | number | 3 | 设备断开连接状态。 |
## ContinuationMode
互联面板连接模式。
**系统能力**:SystemCapability.Ability.DistributedAbilityManager
**参数:**
| 参数名 | 类型 | 值 | 说明 |
| -------- | -------- | -------- | -------- |
| COLLABORATION_SINGLE | number | 0 | 互联面板单选模式。 |
| COLLABORATION_MULTIPLE | number | 1 | 互联面板多选模式。 |
\ No newline at end of file
# ContinuationResult
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## ContinuationResult
表示流转管理入口返回的设备信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.DistributedAbilityManager
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| id | string | 是 | 是 | 表示设备标识。|
| type | string | 是 | 是 | 表示设备类型。 |
| name | string | 是 | 是 | 表示设备名称。 |
\ No newline at end of file
...@@ -5,12 +5,6 @@ ...@@ -5,12 +5,6 @@
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在FA模型下使用。 > 本模块接口仅可在FA模型下使用。
## 导入模块
```js
import featureAbility from "@ohos.ability.featureAbility";
```
## 使用说明 ## 使用说明
使用前根据具体情况引入如下模块 使用前根据具体情况引入如下模块
......
...@@ -7,12 +7,6 @@ EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件 ...@@ -7,12 +7,6 @@ EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```js
import Ability from '@ohos.application.Ability'
```
## 使用说明 ## 使用说明
​在使用eventHub的功能前,需要通过Ability实例的成员变量context获取。 ​在使用eventHub的功能前,需要通过Ability实例的成员变量context获取。
......
...@@ -9,14 +9,6 @@ ExtensionContext模块提供扩展的上下文的能力,包括允许访问特 ...@@ -9,14 +9,6 @@ ExtensionContext模块提供扩展的上下文的能力,包括允许访问特
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
Extension的上下文环境,继承自Context。
## 导入模块
```js
import FormExtension from '@ohos.application.FormExtension';
```
## 属性 ## 属性
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -5,13 +5,7 @@ ExtensionRunningInfo模块提供对Extension运行的相关信息和类型进行 ...@@ -5,13 +5,7 @@ ExtensionRunningInfo模块提供对Extension运行的相关信息和类型进行
> **说明:** > **说明:**
> >
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口均为系统接口,三方应用不支持调用
## 导入模块
```js
import abilitymanager from '@ohos.application.abilityManager';
```
## 使用说明 ## 使用说明
...@@ -25,8 +19,7 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { ...@@ -25,8 +19,7 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
}); });
``` ```
## 属性
### 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -216,7 +216,6 @@ featureAbility.startAbilityForResult( ...@@ -216,7 +216,6 @@ featureAbility.startAbilityForResult(
mykey7: true, mykey7: true,
}, },
}, },
requestCode: 2,
}, },
).then((data) => { ).then((data) => {
console.info("==========================>startAbilityForResult=======================>"); console.info("==========================>startAbilityForResult=======================>");
...@@ -507,9 +506,11 @@ connectAbility(request: Want, options:ConnectOptions): number ...@@ -507,9 +506,11 @@ connectAbility(request: Want, options:ConnectOptions): number
| 名称 | 类型 | 必填 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| ------- | -------------- | ---- | --------------------- | | ------- | -------------- | ---- | --------------------- |
| request | [Want](js-apis-application-Want.md) | 是 | 表示被连接的ServiceAbility。 | | request | [Want](js-apis-application-Want.md) | 是 | 表示被连接的ServiceAbility。 |
| options | ConnectOptions | 是 | 被指定的回调方法。 | | options | [ConnectOptions](#connectoptions) | 是 | 被指定的回调方法。 |
**Want类型说明:** ## Want
want类型说明
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
...@@ -519,7 +520,9 @@ connectAbility(request: Want, options:ConnectOptions): number ...@@ -519,7 +520,9 @@ connectAbility(request: Want, options:ConnectOptions): number
| bundleName | 只读 | string | 是 | 表示被连接的ServiceAbility的包名。 | | bundleName | 只读 | string | 是 | 表示被连接的ServiceAbility的包名。 |
| abilityName | 只读 | string | 是 | 表示被连接的ServiceAbility的类名。 | | abilityName | 只读 | string | 是 | 表示被连接的ServiceAbility的类名。 |
**ConnectOptions类型说明:** ## ConnectOptions
ConnectOptions类型说明
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
...@@ -937,10 +940,10 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY ...@@ -937,10 +940,10 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY
| FLAG_ABILITY_CONTINUATION | 0x00000008 | 确定是否可以将本地设备上的功能迁移到远程设备。 | | FLAG_ABILITY_CONTINUATION | 0x00000008 | 确定是否可以将本地设备上的功能迁移到远程设备。 |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | 指定组件是否属于OHOS。 | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | 指定组件是否属于OHOS。 |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | 指定是否启动某个能力。 | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | 指定是否启动某个能力。 |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | 指示URI上可能持久化的授权。 | | FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | 指示URI上可能持久化的授权。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | 按照前缀匹配的方式验证URI权限。 | | FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | 按照前缀匹配的方式验证URI权限。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | 支持分布式调度系统中的多设备启动。 | | FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | 支持分布式调度系统中的多设备启动。 |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | 指示无论主机应用程序是否已启动,都将启动使用服务模板的功能。 | | FLAG_START_FOREGROUND_ABILITY | 0x00000200 | 指示无论主机应用程序是否已启动,都将启动使用服务模板的功能。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | 表示迁移是可拉回的。 |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | 如果未安装指定的功能,请安装该功能。 |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | 如果未安装,使用后台模式安装该功能。 |
......
...@@ -9,11 +9,9 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。 ...@@ -9,11 +9,9 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块 ## 使用说明
```js FormExtensionContext模块是FormExtension的上下文环境,继承自ExtensionContext。
import FormExtension from '@ohos.application.FormExtension';
```
## FormExtensionContext.updateForm ## FormExtensionContext.updateForm
...@@ -86,3 +84,74 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr ...@@ -86,3 +84,74 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr
} }
``` ```
## FormExtensionContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
拉起一个卡片所属应用的Ability。
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------| --------------------------------- | ---- | -------------------------------------- |
| want| [Want](js-apis-application-Want.md) | 是 | 包含bundleName,abilityName以及用户自定参数用于拉起Ability。 |
| callback| AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
**示例:**
```js
var want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want, function(err) {
console.info(err.code);
})
```
## FormExtensionContext.startAbility
startAbility(want: Want): Promise&lt;void&gt;
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------| --------------------------------- | ---- | -------------------------------------- |
| want| [Want](js-apis-application-Want.md) | 是 | 包含bundleName,abilityName以及用户自定参数用于拉起Ability。 |
**返回值:**
| 类型 | 说明 |
| ------------ | ---------------------------------- |
| Promise&lt;void&lt; | Promise实例,返回接口调用是否成功的结果。 |
**示例:**
```js
var want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
console.info("StartAbility failed");
});
```
\ No newline at end of file
...@@ -857,7 +857,7 @@ acquireFormState(want: Want, callback: AsyncCallback&lt;formInfo.FormStateInfo&g ...@@ -857,7 +857,7 @@ acquireFormState(want: Want, callback: AsyncCallback&lt;formInfo.FormStateInfo&g
获取卡片状态 获取卡片状态
**需要权限**:ohos.permission.REQUIRE_FORM和ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **需要权限**:ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED.
**系统能力**:SystemCapability.Ability.Form **系统能力**:SystemCapability.Ability.Form
......
# 数据请求 # 数据请求
>![](public_sys-resources/icon-note.gif) **说明:** 本模块提供http数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
>**说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> >
...@@ -94,7 +96,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void ...@@ -94,7 +96,7 @@ request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------- | ---- | ----------------------- | | -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | 是 | 发起网络请求的URL地址。 | | url | string | 是 | 发起网络请求的URL地址。 |
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 |
...@@ -170,14 +172,14 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> ...@@ -170,14 +172,14 @@ request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\>
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------ | ---- | -------------------------------------------------- | | ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | 是 | 发起网络请求的URL地址。 | | url | string | 是 | 发起网络请求的URL地址。 |
| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | | options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| :-------------------- | :-------------------------------- | | :------------------------------------- | :-------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | | Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 |
...@@ -225,7 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void ...@@ -225,7 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void
订阅HTTP Response Header 事件。 订阅HTTP Response Header 事件。
>![](public_sys-resources/icon-note.gif) **说明:** >![](public_sys-resources/icon-note.gif) **说明:**
> 此接口已废弃,建议使用[on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8)替代。 >此接口已废弃,建议使用[on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8)替代。
**系统能力**:SystemCapability.Communication.NetStack **系统能力**:SystemCapability.Communication.NetStack
...@@ -354,7 +356,7 @@ httpRequest.once('headersReceive', (header) => { ...@@ -354,7 +356,7 @@ httpRequest.once('headersReceive', (header) => {
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetStack。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式。 | | method | [RequestMethod](#requestmethod) | 否 | 请求方式。 |
| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>8+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>8+</sup> | | extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | 否 | 发送请求的额外数据。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求的参数补充,参数内容会拼接到URL中进行发送。<sup>8+</sup><br />- 开发者传入string对象,开发者需要自行编码,将编码后的string传入。<sup>8+</sup> |
| header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 | | header | Object | 否 | HTTP请求头字段。默认{'Content-Type': 'application/json'}。 |
...@@ -431,7 +433,18 @@ request方法回调函数的返回值类型。 ...@@ -431,7 +433,18 @@ request方法回调函数的返回值类型。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| result | string \| Object \| ArrayBuffer<sup>8+</sup> | 是 | Http请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需Http响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string | | result | string \| Object \| ArrayBuffer<sup>8+</sup> | 是 | Http请求根据响应头中Content-type类型返回对应的响应格式内容:<br />- application/json:返回JSON格式的字符串,如需Http响应具体内容,需开发者自行解析<br />- application/octet-stream:ArrayBuffer<br />- 其他:string |
| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码如下:<br />- 200:通用错误<br />- 202:参数错误<br />- 300:I/O错误 | | responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。错误码参考[Response错误码](#response常用错误码) |
| header | Object | 是 | 发起http请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; | | header | Object | 是 | 发起http请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- Content-Type:header['Content-Type'];<br />- Status-Line:header['Status-Line'];<br />- Date:header.Date/header['Date'];<br />- Server:header.Server/header['Server']; |
| cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 | | cookies<sup>8+</sup> | Array\<string\> | 是 | 服务器返回的 cookies。 |
## Response常用错误码
| 错误码 | 说明 |
| ------ | ------------------------------------------------------------ |
| -1 | 参数错误。 |
| 3 | URL格式错误。 |
| 4 | 构建时无法找到内置的请求功能、协议或选项。 |
| 5 | 无法解析代理。 |
| 6 | 无法解析主机。 |
| 7 | 无法连接代理或主机。 |
...@@ -33,6 +33,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\<Pi ...@@ -33,6 +33,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\<Pi
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts) image.createPixelMap(color, opts)
.then((pixelmap) => { .then((pixelmap) => {
...@@ -59,6 +60,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As ...@@ -59,6 +60,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => { image.createPixelMap(color, opts, (pixelmap) => {
}) })
...@@ -99,10 +101,11 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\<void> ...@@ -99,10 +101,11 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\<void>
**示例:** **示例:**
```js ```js
pixelmap.readPixelsToBuffer(ReadBuffer).then(() => { const readBuffer = new ArrayBuffer(400);
console.log('readPixelsToBuffer succeeded.'); //符合条件则进入 pixelmap.readPixelsToBuffer(readBuffer).then(() => {
console.log('Succeeded in reading image pixel data.'); //符合条件则进入
}).catch(error => { }).catch(error => {
console.log('readPixelsToBuffer failed.'); //不符合条件则进入 console.log('Failed to read image pixel data.'); //不符合条件则进入
}) })
``` ```
...@@ -124,11 +127,12 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\<void>): void ...@@ -124,11 +127,12 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
pixelmap.readPixelsToBuffer(ReadBuffer, (err, res) => { const readBuffer = new ArrayBuffer(400);
pixelmap.readPixelsToBuffer(readBuffer, (err, res) => {
if(err) { if(err) {
console.log('readPixelsToBuffer failed.'); //不符合条件则进入 console.log('Failed to read image pixel data.'); //不符合条件则进入
} else { } else {
console.log('readPixelsToBuffer succeeded.'); //符合条件则进入 console.log('Succeeded in reading image pixel data.'); //符合条件则进入
} }
}) })
``` ```
...@@ -156,10 +160,11 @@ readPixels(area: PositionArea): Promise\<void> ...@@ -156,10 +160,11 @@ readPixels(area: PositionArea): Promise\<void>
**示例:** **示例:**
```js ```js
pixelmap.readPixels(Area).then((data) => { const area = new ArrayBuffer(400);
console.log('readPixels succeeded.'); //符合条件则进入 pixelmap.readPixels(area).then(() => {
console.log('Succeeded in reading the image data in the area.'); //符合条件则进入
}).catch(error => { }).catch(error => {
console.log('readPixels failed.'); //不符合条件则进入 console.log('Failed to read the image data in the area.'); //不符合条件则进入
}) })
``` ```
...@@ -181,6 +186,8 @@ readPixels(area: PositionArea, callback: AsyncCallback\<void>): void ...@@ -181,6 +186,8 @@ readPixels(area: PositionArea, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => { image.createPixelMap(color, opts, (err, pixelmap) => {
if(pixelmap == undefined){ if(pixelmap == undefined){
...@@ -221,6 +228,7 @@ writePixels(area: PositionArea): Promise\<void> ...@@ -221,6 +228,7 @@ writePixels(area: PositionArea): Promise\<void>
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts) image.createPixelMap(color, opts)
.then( pixelmap => { .then( pixelmap => {
...@@ -263,14 +271,15 @@ writePixels(area: PositionArea, callback: AsyncCallback\<void>): void ...@@ -263,14 +271,15 @@ writePixels(area: PositionArea, callback: AsyncCallback\<void>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------------ | ---- | ------------------------------ | | --------- | ------------------------------ | ---- | ------------------------------ |
| area | [PositionArea](#positionarea7) | 是 | 区域,根据区域写入。 | | area | [PositionArea](#positionarea7) | 是 | 区域,根据区域写入。 |
| callback: | AsyncCallback\<void> | 是 | 获取回调,失败时error会返回错误信息。 | | callback: | AsyncCallback\<void> | 是 | 获取回调,失败时返回错误信息。 |
**示例:** **示例:**
```js ```js
pixelmap.writePixels(Area, (error) => { const area = new ArrayBuffer(400);
pixelmap.writePixels(area, (error) => {
if (error!=undefined) { if (error!=undefined) {
console.info('writePixels failed.'); console.info('Failed to write pixelmap into the specified area.');
} else { } else {
const readArea = { const readArea = {
pixels: new ArrayBuffer(20), pixels: new ArrayBuffer(20),
...@@ -305,7 +314,10 @@ writeBufferToPixels(src: ArrayBuffer): Promise\<void> ...@@ -305,7 +314,10 @@ writeBufferToPixels(src: ArrayBuffer): Promise\<void>
**示例:** **示例:**
```js ```js
PixelMap.writeBufferToPixels(color).then(() => { const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Unit8Array(color);
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.");
...@@ -330,7 +342,10 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\<void>): void ...@@ -330,7 +342,10 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
PixelMap.writeBufferToPixels(color, function(err) { const color = new ArrayBuffer(96);\
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Unit8Array(color);
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;
...@@ -357,7 +372,8 @@ getImageInfo(): Promise\<ImageInfo> ...@@ -357,7 +372,8 @@ getImageInfo(): Promise\<ImageInfo>
**示例:** **示例:**
```js ```js
PixelMap.getImageInfo().then(function(info) { const pixelMap = new ArrayBuffer(400);
pixelMap.getImageInfo().then(function(info) {
console.log("Succeeded in obtaining the image pixel map information."); console.log("Succeeded in obtaining the image pixel map information.");
}).catch((err) => { }).catch((err) => {
console.error("Failed to obtain the image pixel map information."); console.error("Failed to obtain the image pixel map information.");
...@@ -382,9 +398,7 @@ getImageInfo(callback: AsyncCallback\<ImageInfo>): void ...@@ -382,9 +398,7 @@ getImageInfo(callback: AsyncCallback\<ImageInfo>): void
```js ```js
pixelmap.getImageInfo((imageInfo) => { pixelmap.getImageInfo((imageInfo) => {
console.log("getImageInfo succeeded."); console.log("Succeeded in obtaining the image pixel map information..");
}).catch((err) => {
console.error("getImageInfo failed.");
}) })
``` ```
...@@ -405,7 +419,10 @@ getBytesNumberPerRow(): number ...@@ -405,7 +419,10 @@ getBytesNumberPerRow(): number
**示例:** **示例:**
```js ```js
image.createPixelMap(clolr, opts, (err,pixelmap) => { const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err,pixelmap) => {
let rowCount = pixelmap.getBytesNumberPerRow(); let rowCount = pixelmap.getBytesNumberPerRow();
}) })
``` ```
...@@ -447,11 +464,14 @@ release():Promise\<void> ...@@ -447,11 +464,14 @@ release():Promise\<void>
**示例:** **示例:**
```js ```js
const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => { image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => { pixelmap.release().then(() => {
console.log('release succeeded.'); console.log('Succeeded in releasing pixelmap object.');
}).catch(error => { }).catch(error => {
console.log('release failed.'); console.log('Failed to release pixelmap object.');
}) })
}) })
``` ```
...@@ -473,11 +493,14 @@ release(callback: AsyncCallback\<void>): void ...@@ -473,11 +493,14 @@ release(callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
const color = new ArrayBuffer(96);
let bufferArr = new Unit8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => { image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => { pixelmap.release().then(() => {
console.log('release succeeded.'); console.log('Succeeded in releasing pixelmap object.');
}).catch(error => { }).catch(error => {
console.log('release failed.'); console.log('Failed to release pixelmap object.');
}) })
}) })
``` ```
...@@ -592,9 +615,7 @@ getImageInfo(callback: AsyncCallback\<ImageInfo>): void ...@@ -592,9 +615,7 @@ getImageInfo(callback: AsyncCallback\<ImageInfo>): void
```js ```js
imageSourceApi.getImageInfo(imageInfo => { imageSourceApi.getImageInfo(imageInfo => {
console.log('getImageInfo succeeded.'); console.log('Succeeded in obtaining the image information.');
}).catch(error => {
console.log('getImageInfo failed.');
}) })
``` ```
...@@ -623,9 +644,9 @@ getImageInfo(index?: number): Promise\<ImageInfo> ...@@ -623,9 +644,9 @@ getImageInfo(index?: number): Promise\<ImageInfo>
```js ```js
imageSourceApi.getImageInfo(0) imageSourceApi.getImageInfo(0)
.then(imageInfo => { .then(imageInfo => {
console.log('getImageInfo succeeded.'); console.log('Succeeded in obtaining the image information.');
}).catch(error => { }).catch(error => {
console.log('getImageInfo failed.'); console.log('Failed to obtain the image information.');
}) })
``` ```
...@@ -655,9 +676,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\<string ...@@ -655,9 +676,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\<string
```js ```js
imageSourceApi.getImageProperty("BitsPerSample") imageSourceApi.getImageProperty("BitsPerSample")
.then(data => { .then(data => {
console.log('getImageProperty succeeded.'); console.log('Succeeded in getting the value of the specified attribute key of the image.');
}).catch(error => {
console.log('getImageProperty failed.');
}) })
``` ```
...@@ -681,9 +700,9 @@ getImageProperty(key:string, callback: AsyncCallback\<string>): void ...@@ -681,9 +700,9 @@ getImageProperty(key:string, callback: AsyncCallback\<string>): void
```js ```js
imageSourceApi.getImageProperty("BitsPerSample",(error,data) => { imageSourceApi.getImageProperty("BitsPerSample",(error,data) => {
if(error) { if(error) {
console.log('getImageProperty failed.'); console.log('Failed to get the value of the specified attribute key of the image.');
} else { } else {
console.log('getImageProperty succeeded.'); console.log('Succeeded in getting the value of the specified attribute key of the image.');
} }
}) })
``` ```
...@@ -707,11 +726,12 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa ...@@ -707,11 +726,12 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa
**示例:** **示例:**
```js ```js
imageSourceApi.getImageProperty("BitsPerSample",Property,(error,data) => { const property = new ArrayBuffer(400);
imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
if(error) { if(error) {
console.log('getImageProperty failed.'); console.log('Failed to get the value of the specified attribute key of the image.');
} else { } else {
console.log('getImageProperty succeeded.'); console.log('Succeeded in getting the value of the specified attribute key of the image.');
} }
}) })
``` ```
...@@ -740,9 +760,9 @@ createPixelMap(options?: DecodingOptions): Promise\<PixelMap> ...@@ -740,9 +760,9 @@ createPixelMap(options?: DecodingOptions): Promise\<PixelMap>
```js ```js
imageSourceApi.createPixelMap().then(pixelmap => { imageSourceApi.createPixelMap().then(pixelmap => {
console.log('createPixelMap succeeded.'); console.log('Succeeded in creating pixelmap object through image decoding parameters.');
}).catch(error => { }).catch(error => {
console.log('createPixelMap failed.'); console.log('Failed to create pixelmap object through image decoding parameters.');
}) })
``` ```
...@@ -764,9 +784,9 @@ createPixelMap(callback: AsyncCallback\<PixelMap>): void ...@@ -764,9 +784,9 @@ createPixelMap(callback: AsyncCallback\<PixelMap>): void
```js ```js
imageSourceApi.createPixelMap(pixelmap => { imageSourceApi.createPixelMap(pixelmap => {
console.log('createPixelMap succeeded.'); console.log('Succeeded in creating pixelmap object.');
}).catch(error => { }).catch(error => {
console.log('createPixelMap failed.'); console.log('Failed to create pixelmap object.');
}) })
``` ```
...@@ -788,10 +808,9 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\<PixelMap>): vo ...@@ -788,10 +808,9 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\<PixelMap>): vo
**示例:** **示例:**
```js ```js
const decodingOptions = new ArrayBuffer(400);
imageSourceApi.createPixelMap(decodingOptions, pixelmap => { imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
console.log('createPixelMap succeeded.'); console.log('Succeeded in creating pixelmap object.');
}).catch(error => {
console.log('createPixelMap failed.');
}) })
``` ```
...@@ -814,8 +833,6 @@ release(callback: AsyncCallback\<void>): void ...@@ -814,8 +833,6 @@ release(callback: AsyncCallback\<void>): void
```js ```js
imageSourceApi.release(() => { imageSourceApi.release(() => {
console.log('release succeeded.'); console.log('release succeeded.');
}).catch(error => {
console.log('release failed.');
}) })
``` ```
...@@ -837,9 +854,9 @@ release(): Promise\<void> ...@@ -837,9 +854,9 @@ release(): Promise\<void>
```js ```js
imageSourceApi.release().then(()=>{ imageSourceApi.release().then(()=>{
console.log('release succeeded.'); console.log('Succeeded in releasing the image source instance.');
}).catch(error => { }).catch(error => {
console.log('release failed.'); console.log('Failed to release the image source instance.');
}) })
``` ```
...@@ -895,7 +912,8 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<Arr ...@@ -895,7 +912,8 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<Arr
```js ```js
let packOpts = { format:"image/jpeg", quality:98 }; let packOpts = { format:"image/jpeg", quality:98 };
imagePackerApi.packing(ImageSourceApi, packOpts, data => {}) const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts, data => {})
``` ```
### packing ### packing
...@@ -922,8 +940,9 @@ packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer> ...@@ -922,8 +940,9 @@ packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer>
**示例:** **示例:**
```js ```js
let packOpts = { format:["image/jpeg"], quality:98 } let packOpts = { format:"image/jpeg", quality:98 }
imagePackerApi.packing(ImageSourceApi, packOpts) const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.log('packing succeeded.'); console.log('packing succeeded.');
}).catch(error => { }).catch(error => {
...@@ -950,11 +969,12 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\<ArrayB ...@@ -950,11 +969,12 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\<ArrayB
**示例:** **示例:**
```js ```js
let packOpts = { format:["image/jpeg"], quality:98 } let packOpts = { format:"image/jpeg", quality:98 }
imagePackerApi.packing(PixelMapApi, packOpts, data => { const pixelMapApi = new ArrayBuffer(400);
console.log('packing succeeded.'); imagePackerApi.packing(pixelMapApi, packOpts, data => {
console.log('Succeeded in packing the image.');
}).catch(error => { }).catch(error => {
console.log('packing failed.'); console.log('Failed to pack the image.');
}) })
``` ```
...@@ -982,12 +1002,13 @@ packing(source: PixelMap, option: PackingOption): Promise\<ArrayBuffer> ...@@ -982,12 +1002,13 @@ packing(source: PixelMap, option: PackingOption): Promise\<ArrayBuffer>
**示例:** **示例:**
```js ```js
let packOpts = { format:["image/jpeg"], quality:98 } let packOpts = { format:"image/jpeg", quality:98 }
imagePackerApi.packing(PixelMapApi, packOpts) const pixelMapApi = new ArrayBuffer(400);
imagePackerApi.packing(pixelMapApi, packOpts)
.then( data => { .then( data => {
console.log('packing succeeded.'); console.log('Succeeded in packing the image.');
}).catch(error => { }).catch(error => {
console.log('packing failed.'); console.log('Failed to pack the image..');
}) })
``` ```
...@@ -1009,9 +1030,7 @@ release(callback: AsyncCallback\<void>): void ...@@ -1009,9 +1030,7 @@ release(callback: AsyncCallback\<void>): void
```js ```js
imagePackerApi.release(()=>{ imagePackerApi.release(()=>{
console.log('release succeeded.'); console.log('Succeeded in releasing image packaging.');
}).catch(error => {
console.log('release failed.');
}) })
``` ```
...@@ -1033,9 +1052,9 @@ release(): Promise\<void> ...@@ -1033,9 +1052,9 @@ release(): Promise\<void>
```js ```js
imagePackerApi.release().then(()=>{ imagePackerApi.release().then(()=>{
console.log('release succeeded.'); console.log('Succeeded in releasing image packaging.');
}).catch((error)=>{ }).catch((error)=>{
console.log('release failed.'); console.log('Failed to release image packaging.');
}) })
``` ```
...@@ -1101,7 +1120,7 @@ getReceivingSurfaceId(callback: AsyncCallback\<string>): void ...@@ -1101,7 +1120,7 @@ getReceivingSurfaceId(callback: AsyncCallback\<string>): void
**示例:** **示例:**
```js ```js
receiver.getReceivingSurfaceId((err, id) => { receiver.getReceivingSurfaceId((err, id) => {
if(err) { if(err) {
console.log('getReceivingSurfaceId failed.'); console.log('getReceivingSurfaceId failed.');
} else { } else {
...@@ -1516,7 +1535,7 @@ PixelMap的初始化选项。 ...@@ -1516,7 +1535,7 @@ PixelMap的初始化选项。
| desiredSize | [Size](#size) | 是 | 是 | 期望输出大小。 | | desiredSize | [Size](#size) | 是 | 是 | 期望输出大小。 |
| desiredRegion | [Region](#region7) | 是 | 是 | 解码区域。 | | desiredRegion | [Region](#region7) | 是 | 是 | 解码区域。 |
| desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | 是 | 是 | 解码的像素格式。 | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | 是 | 是 | 解码的像素格式。 |
| index | number | 是 | 是 | 解码图片序号 | | index | number | 是 | 是 | 解码图片序号。 |
## Region<sup>7+</sup> ## Region<sup>7+</sup>
......
# 网络连接管理 # 网络连接管理
网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。
> **说明:** > **说明:**
> >
...@@ -79,7 +80,7 @@ hasDefaultNet(callback: AsyncCallback\<boolean>): void ...@@ -79,7 +80,7 @@ hasDefaultNet(callback: AsyncCallback\<boolean>): void
```js ```js
connection.hasDefaultNet(function (error, has) { connection.hasDefaultNet(function (error, has) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(has) console.log('has: ' + has)
}) })
``` ```
...@@ -101,7 +102,7 @@ hasDefaultNet(): Promise\<boolean> ...@@ -101,7 +102,7 @@ hasDefaultNet(): Promise\<boolean>
```js ```js
connection.hasDefaultNet().then(function (has) { connection.hasDefaultNet().then(function (has) {
console.log(has) console.log('has: ' + has)
}) })
``` ```
...@@ -446,6 +447,105 @@ connection.getAddressesByName(host).then(function (addresses) { ...@@ -446,6 +447,105 @@ connection.getAddressesByName(host).then(function (addresses) {
}) })
``` ```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
开启飞行模式,使用callback方式作为异步方法。
该接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:**
```js
connection.enableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.enableAirplaneMode
enableAirplaneMode(): Promise\<void>
开启飞行模式,使用Promise方式作为异步方法。
该接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 |
**示例:**
```js
connection.enableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
关闭飞行模式,使用callback方式作为异步方法。
该接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例:**
```js
connection.disableAirplaneMode(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.disableAirplaneMode
disableAirplaneMode(): Promise\<void>
关闭飞行模式,使用Promise方式作为异步方法。
该接口为系统接口。
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 |
**示例:**
```js
connection.disableAirplaneMode().then(function (error) {
console.log(JSON.stringify(error))
})
```
## connection.createNetConnection ## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
...@@ -476,7 +576,7 @@ let netConnection = connection.createNetConnection() ...@@ -476,7 +576,7 @@ let netConnection = connection.createNetConnection()
// 关注蜂窝网络 // 关注蜂窝网络
let netConnectionCellular = connection.createNetConnection({ let netConnectionCellular = connection.createNetConnection({
netCapabilities: { netCapabilities: {
bearerTypes: [NetBearType.BEARER_CELLULAR] bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
} }
}) })
``` ```
......
...@@ -2871,6 +2871,8 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number): Promis ...@@ -2871,6 +2871,8 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number): Promis
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**需要权限**: ohos.permission.NOTIFICATION_CONTROLLER,ohos.permission.NOTIFICATION_AGENT_CONTROLLER
**参数:** **参数:**
...@@ -3024,12 +3026,14 @@ Notification.isNotificationSlotEnabled( ...@@ -3024,12 +3026,14 @@ Notification.isNotificationSlotEnabled(
### onConsume ### onConsume
onConsume?:(data: [SubscribeCallbackData](#subscribecallbackdata)) onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void
接收通知回调函数。 接收通知回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -3071,12 +3075,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3071,12 +3075,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onCancel ### onCancel
onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void
删除通知回调函数。 删除通知回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -3109,12 +3115,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3109,12 +3115,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onUpdate ### onUpdate
onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void
更新通知排序回调函数。 更新通知排序回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -3145,12 +3153,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3145,12 +3153,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onConnect ### onConnect
onConnect?:void onConnect?:() => void
注册订阅回调函数。 注册订阅回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**示例:** **示例:**
```javascript ```javascript
...@@ -3175,12 +3185,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3175,12 +3185,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onDisconnect ### onDisconnect
onDisconnect?:void onDisconnect?:() => void
取消订阅回调函数。 取消订阅回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**示例:** **示例:**
```javascript ```javascript
...@@ -3205,12 +3217,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3205,12 +3217,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onDestroy ### onDestroy
onDestroy?:void onDestroy?:() => void
服务失联回调函数。 服务失联回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**示例:** **示例:**
```javascript ```javascript
...@@ -3235,12 +3249,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3235,12 +3249,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onDoNotDisturbDateChange<sup>8+</sup> ### onDoNotDisturbDateChange<sup>8+</sup>
onDoNotDisturbDateChange?:(mode: Notification.[DoNotDisturbDate](#donotdisturbdate8)) onDoNotDisturbDateChange?:(mode: Notification.[DoNotDisturbDate](#donotdisturbdate8)) => void
免打扰时间选项变更回调函数。 免打扰时间选项变更回调函数。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -3271,12 +3287,14 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3271,12 +3287,14 @@ Notification.subscribe(subscriber, subscribeCallback);
### onEnabledNotificationChanged<sup>8+</sup> ### onEnabledNotificationChanged<sup>8+</sup>
onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) => void
监听应用通知使能变化。 监听应用通知使能变化。
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -3353,7 +3371,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3353,7 +3371,7 @@ Notification.subscribe(subscriber, subscribeCallback);
**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification
**系统API**此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------ | ---------------- | ------------------------------------------ | | ------------ | ---------------- | ------------------------------------------ |
...@@ -3556,13 +3574,13 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3556,13 +3574,13 @@ Notification.subscribe(subscriber, subscribeCallback);
| creatorPid | 是 | 否 | number | 否 | 创建通知的PID。 | | creatorPid | 是 | 否 | number | 否 | 创建通知的PID。 |
| creatorUserId<sup>8+</sup>| 是 | 否 | number | 否 | 创建通知的UserId。 | | creatorUserId<sup>8+</sup>| 是 | 否 | number | 否 | 创建通知的UserId。 |
| hashCode | 是 | 否 | string | 否 | 通知唯一标识。 | | hashCode | 是 | 否 | string | 否 | 通知唯一标识。 |
| classification | 是 | 是 | string | 否 | 通知分类。 | | classification | 是 | 是 | string | 否 | 通知分类。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| groupName<sup>8+</sup>| 是 | 是 | string | 否 | 组通知名称。 | | groupName<sup>8+</sup>| 是 | 是 | string | 否 | 组通知名称。 |
| template<sup>8+</sup> | 是 | 是 | [NotificationTemplate](#notificationtemplate8) | 否 | 通知模板。 | | template<sup>8+</sup> | 是 | 是 | [NotificationTemplate](#notificationtemplate8) | 否 | 通知模板。 |
| isRemoveAllowed<sup>8+</sup> | 是 | 否 | boolean | 否 | 通知是否能被移除。 | | isRemoveAllowed<sup>8+</sup> | 是 | 否 | boolean | 否 | 通知是否能被移除。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| source<sup>8+</sup> | 是 | 否 | number | 否 | 通知源。 | | source<sup>8+</sup> | 是 | 否 | number | 否 | 通知源。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| distributedOption<sup>8+</sup> | 是 | 是 | [DistributedOptions](#distributedoptions8) | 否 | 分布式通知的选项。 | | distributedOption<sup>8+</sup> | 是 | 是 | [DistributedOptions](#distributedoptions8) | 否 | 分布式通知的选项。 |
| deviceId<sup>8+</sup> | 是 | 否 | string | 否 | 通知源的deviceId。 | | deviceId<sup>8+</sup> | 是 | 否 | string | 否 | 通知源的deviceId。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| notificationFlags<sup>8+</sup> | 是 | 否 | [NotificationFlags](#notificationflags8) | 否 | 获取NotificationFlags。 | | notificationFlags<sup>8+</sup> | 是 | 否 | [NotificationFlags](#notificationflags8) | 否 | 获取NotificationFlags。 |
...@@ -3575,7 +3593,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3575,7 +3593,7 @@ Notification.subscribe(subscriber, subscribeCallback);
| isDistributed | 是 | 是 | boolean | 否 | 是否为分布式通知。 | | isDistributed | 是 | 是 | boolean | 否 | 是否为分布式通知。 |
| supportDisplayDevices | 是 | 是 | Array\<string> | 是 | 可以同步通知到的设备类型。 | | supportDisplayDevices | 是 | 是 | Array\<string> | 是 | 可以同步通知到的设备类型。 |
| supportOperateDevices | 是 | 是 | Array\<string> | 否 | 可以打开通知的设备。 | | supportOperateDevices | 是 | 是 | Array\<string> | 否 | 可以打开通知的设备。 |
| remindType | 是 | 否 | number | 否 | 通知的提醒方式。 | | remindType | 是 | 否 | number | 否 | 通知的提醒方式。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
## NotificationSlot ## NotificationSlot
...@@ -3602,7 +3620,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3602,7 +3620,7 @@ Notification.subscribe(subscriber, subscribeCallback);
**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification
**系统API**此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 可读 | 可写 | 类型 | 必填 | 描述 | | 名称 | 可读 | 可写 | 类型 | 必填 | 描述 |
| -------- | ---- | --- | ------------------------------------- | ---- | ------------ | | -------- | ---- | --- | ------------------------------------- | ---- | ------------ |
...@@ -3627,7 +3645,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3627,7 +3645,7 @@ Notification.subscribe(subscriber, subscribeCallback);
**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification
**系统API**此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 可读 | 可写 | 类型 | 必填 | 描述 | | 名称 | 可读 | 可写 | 类型 | 必填 | 描述 |
| ----------- | --- | ---- | --------------- | ---- | ------------------------------- | | ----------- | --- | ---- | --------------- | ---- | ------------------------------- |
...@@ -3658,7 +3676,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3658,7 +3676,7 @@ Notification.subscribe(subscriber, subscribeCallback);
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 值 | 描述 | | 名称 | 值 | 描述 |
| -------------------- | --- | --------------------------------- | | -------------------- | --- | --------------------------------- |
...@@ -3672,6 +3690,8 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3672,6 +3690,8 @@ Notification.subscribe(subscriber, subscribeCallback);
**系统能力**:SystemCapability.Notification.Notification **系统能力**:SystemCapability.Notification.Notification
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 值 | 描述 | | 名称 | 值 | 描述 |
| -------------------- | --- | -------------------- | | -------------------- | --- | -------------------- |
| TYPE_NORMAL | 0 | 一般通知。 | | TYPE_NORMAL | 0 | 一般通知。 |
......
# observer # observer
本模块提供订阅管理功能,可以订阅/取消订阅的事件包括:网络状态变化、信号状态变化、通话状态变化、蜂窝数据链路连接状态、蜂窝数据业务的上下行数据流状态、SIM状态变化。
>**说明:** >**说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -70,8 +72,6 @@ off\(type: \'networkStateChange\', callback?: Callback<NetworkState\>\): void; ...@@ -70,8 +72,6 @@ off\(type: \'networkStateChange\', callback?: Callback<NetworkState\>\): void;
取消订阅网络状态变化事件,使用callback方式作为异步方法。 取消订阅网络状态变化事件,使用callback方式作为异步方法。
**需要权限**:ohos.permission.GET_NETWORK_INFO
>**说明:** >**说明:**
> >
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
...@@ -184,8 +184,6 @@ on(type: 'callStateChange', callback: Callback\<{ state: CallState, number: stri ...@@ -184,8 +184,6 @@ on(type: 'callStateChange', callback: Callback\<{ state: CallState, number: stri
订阅通话状态变化事件,使用callback方式作为异步方法。 订阅通话状态变化事件,使用callback方式作为异步方法。
**需要权限**:ohos.permission.READ_CALL_LOG
**系统能力**:SystemCapability.Telephony.StateRegistry **系统能力**:SystemCapability.Telephony.StateRegistry
**参数:** **参数:**
...@@ -210,8 +208,6 @@ on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ st ...@@ -210,8 +208,6 @@ on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ st
订阅通话状态变化事件,使用callback方式作为异步方法。 订阅通话状态变化事件,使用callback方式作为异步方法。
**需要权限**:ohos.permission.READ_CALL_LOG
**系统能力**:SystemCapability.Telephony.StateRegistry **系统能力**:SystemCapability.Telephony.StateRegistry
**参数:** **参数:**
...@@ -237,8 +233,6 @@ off(type: 'callStateChange', callback?: Callback<{ state: CallState, number: str ...@@ -237,8 +233,6 @@ off(type: 'callStateChange', callback?: Callback<{ state: CallState, number: str
取消订阅通话状态变化事件,使用callback方式作为异步方法。 取消订阅通话状态变化事件,使用callback方式作为异步方法。
**需要权限**:ohos.permission.READ_CALL_LOG
>**说明:** >**说明:**
> >
>可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 >可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
......
...@@ -7,12 +7,6 @@ PermissionRequestResult模块提供了权限请求结果的能力。 ...@@ -7,12 +7,6 @@ PermissionRequestResult模块提供了权限请求结果的能力。
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```js
import Ability from '@ohos.application.Ability'
```
## 使用说明 ## 使用说明
通过AbilityContext实例来获取。 通过AbilityContext实例来获取。
......
...@@ -6,12 +6,6 @@ ProcessRunningInfo模块提供对进程运行信息进行设置和查询的能 ...@@ -6,12 +6,6 @@ ProcessRunningInfo模块提供对进程运行信息进行设置和查询的能
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import appManager from '@ohos.application.appManager'
```
## 使用说明 ## 使用说明
通过appManager来获取。 通过appManager来获取。
...@@ -23,7 +17,6 @@ appManager.getProcessRunningInfos((error,data) => { ...@@ -23,7 +17,6 @@ appManager.getProcessRunningInfos((error,data) => {
}); });
``` ```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......
# 网络搜索 # 网络搜索
网络搜索模块提供管理网络搜索的一些基础功能,包括获取当前接入的CS域和PS域无线接入技术、获取网络状态、获取当前选网模式、获取注册网络所在国家的ISO国家码、获取主卡所在卡槽的索引号、获取指定SIM卡槽对应的注册网络信号强度信息列表、获取运营商名称、获取设备的指定卡槽的IMEI、获取设备的指定卡槽的MEID、获取设备的指定卡槽的唯一设备ID,判断当前设备是否支持5G\(NR\)、判断主卡的Radio是否打开等。
>**说明:** >**说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -562,7 +564,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback<void\>): void ...@@ -562,7 +564,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback<void\>): void
设置主卡所在卡槽的索引号,使用callback方式作为异步方法。 设置主卡所在卡槽的索引号,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -573,7 +575,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback<void\>): void ...@@ -573,7 +575,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | -------------------------------------- | | -------- | --------------------- | ---- | -------------------------------------- |
| slotId | number | 是 | 卡槽ID。<br/>- 0:卡槽1<br/>- 1:卡槽2 | | slotId | number | 是 | 卡槽ID。<br/>- 0:卡槽1<br/>- 1:卡槽2 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。当设置成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:** **示例:**
...@@ -591,7 +593,7 @@ setPrimarySlotId\(slotId: number\): Promise\<void\> ...@@ -591,7 +593,7 @@ setPrimarySlotId\(slotId: number\): Promise\<void\>
设置主卡所在卡槽的索引号,使用Promise方式作为异步方法。 设置主卡所在卡槽的索引号,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -607,7 +609,7 @@ setPrimarySlotId\(slotId: number\): Promise\<void\> ...@@ -607,7 +609,7 @@ setPrimarySlotId\(slotId: number\): Promise\<void\>
| 类型 | 说明 | | 类型 | 说明 |
| --------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -627,7 +629,7 @@ getIMEI(callback: AsyncCallback<string\>): void ...@@ -627,7 +629,7 @@ getIMEI(callback: AsyncCallback<string\>): void
获取设备的指定卡槽的IMEI,使用callback方式作为异步方法。 获取设备的指定卡槽的IMEI,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -654,7 +656,7 @@ getIMEI(slotId: number, callback: AsyncCallback<string\>): void ...@@ -654,7 +656,7 @@ getIMEI(slotId: number, callback: AsyncCallback<string\>): void
获取设备的指定卡槽的IMEI,使用callback方式作为异步方法。 获取设备的指定卡槽的IMEI,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -683,7 +685,7 @@ getIMEI(slotId?: number): Promise<string\> ...@@ -683,7 +685,7 @@ getIMEI(slotId?: number): Promise<string\>
获取设备的指定卡槽的IMEI,使用Promise方式作为异步方法。 获取设备的指定卡槽的IMEI,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -699,7 +701,7 @@ getIMEI(slotId?: number): Promise<string\> ...@@ -699,7 +701,7 @@ getIMEI(slotId?: number): Promise<string\>
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | ------------------------------------------ | | ----------------- | ------------------------------------------ |
| Promise\<string\> | Promise对象。返回IMEI;如果IMEI不存在,则返回空字符串。 | | Promise\<string\> | 返回IMEI;如果IMEI不存在,则返回空字符串。 |
**示例:** **示例:**
...@@ -719,7 +721,7 @@ getMEID(callback: AsyncCallback<string\>): void ...@@ -719,7 +721,7 @@ getMEID(callback: AsyncCallback<string\>): void
获取设备的指定卡槽的MEID,使用callback方式作为异步方法。 获取设备的指定卡槽的MEID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -746,7 +748,7 @@ getMEID(slotId: number, callback: AsyncCallback<string\>): void ...@@ -746,7 +748,7 @@ getMEID(slotId: number, callback: AsyncCallback<string\>): void
获取设备的指定卡槽的MEID,使用callback方式作为异步方法。 获取设备的指定卡槽的MEID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -775,7 +777,7 @@ getMEID(slotId?: number): Promise<string\> ...@@ -775,7 +777,7 @@ getMEID(slotId?: number): Promise<string\>
获取设备的指定卡槽的MEID,使用Promise方式作为异步方法。 获取设备的指定卡槽的MEID,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -811,7 +813,7 @@ getUniqueDeviceId(callback: AsyncCallback<string\>): void ...@@ -811,7 +813,7 @@ getUniqueDeviceId(callback: AsyncCallback<string\>): void
获取设备的指定卡槽的唯一设备ID,使用callback方式作为异步方法。 获取设备的指定卡槽的唯一设备ID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -838,7 +840,7 @@ getUniqueDeviceId(slotId: number, callback: AsyncCallback<string\>): void ...@@ -838,7 +840,7 @@ getUniqueDeviceId(slotId: number, callback: AsyncCallback<string\>): void
获取设备的指定卡槽的唯一设备ID,使用callback方式作为异步方法。 获取设备的指定卡槽的唯一设备ID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -867,7 +869,7 @@ getUniqueDeviceId(slotId?: number): Promise<string\> ...@@ -867,7 +869,7 @@ getUniqueDeviceId(slotId?: number): Promise<string\>
获取设备的指定卡槽的唯一设备ID,使用Promise方式作为异步方法。 获取设备的指定卡槽的唯一设备ID,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
......
...@@ -198,11 +198,13 @@ onReconnect(want: Want): void; ...@@ -198,11 +198,13 @@ onReconnect(want: Want): void;
} }
``` ```
## ServiceExtensionAbility.onReconnect ## ServiceExtensionAbility.onConfigurationUpdated
onConfigurationUpdated(config: Configuration): void; onConfigurationUpdated(config: Configuration): void;
**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
...@@ -213,7 +215,7 @@ onConfigurationUpdated(config: Configuration): void; ...@@ -213,7 +215,7 @@ onConfigurationUpdated(config: Configuration): void;
**示例:** **示例:**
```js ```js
class myAbility extends Ability { class ServiceExt extends ServiceExtension {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); console.log('onConfigurationUpdated, config:' + JSON.stringify(config));
} }
...@@ -226,7 +228,9 @@ dump(params: Array\<string>): Array\<string>; ...@@ -226,7 +228,9 @@ dump(params: Array\<string>): Array\<string>;
转储客户端信息时调用。 转储客户端信息时调用。
**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
...@@ -237,7 +241,7 @@ dump(params: Array\<string>): Array\<string>; ...@@ -237,7 +241,7 @@ dump(params: Array\<string>): Array\<string>;
**示例:** **示例:**
```js ```js
class myAbility extends Ability { class ServiceExt extends ServiceExtension {
dump(params) { dump(params) {
console.log('dump, params:' + JSON.stringify(params)); console.log('dump, params:' + JSON.stringify(params));
return ["params"] return ["params"]
......
...@@ -9,11 +9,19 @@ ServiceExtensionContext模块提供ServiceExtension具有的能力和接口, ...@@ -9,11 +9,19 @@ ServiceExtensionContext模块提供ServiceExtension具有的能力和接口,
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块 ## 使用说明
``` ServiceExtensionContext模块是ServiceExtension的上下文环境,继承自ExtensionContext。
import ExtensionContext from '@ohos.application.ServiceExtensionAbility';
``` ## 属性
表示访问应用程序资源的能力。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| resourceManager | resmgr.ResourceManager; | 是 | 否 | ResourceManager对象。 |
## startAbility ## startAbility
...@@ -49,8 +57,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void; ...@@ -49,8 +57,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
``` ```
## startAbility
## ServiceExtensionContext.startAbility
startAbility(want: Want): Promise&lt;void&gt;; startAbility(want: Want): Promise&lt;void&gt;;
...@@ -89,8 +96,149 @@ startAbility(want: Want): Promise&lt;void&gt;; ...@@ -89,8 +96,149 @@ startAbility(want: Want): Promise&lt;void&gt;;
}); });
} }
} }
```
## startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
启动Ability。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 |
| callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动结果。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
};
this.context.startAbility(want, options, (error) => {
console.log("error.code = " + error.code)
})
```
## ServiceExtensionContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void\>): void;
根据account启动Ability(callback形式)。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| callback | AsyncCallback\<void\> | 是 | 启动Ability的回调函数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
this.context.startAbilityWithAccount(want, accountId, (err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
});
```
## ServiceExtensionContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
根据account启动Ability(callback形式)。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\<void\> | 是 | 启动Ability的回调函数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityWithAccount(want, accountId, options, (err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
});
```
## ServiceExtensionContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void\>;
根据account启动Ability(Promise形式)。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
windowMode: 0,
};
this.context.startAbilityWithAccount(want, accountId, options)
.then((data) => {
console.log('---------- startAbilityWithAccount success, data: -----------', data);
})
.catch((err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err);
})
``` ```
...@@ -158,7 +306,6 @@ terminateSelf(): Promise&lt;void&gt;; ...@@ -158,7 +306,6 @@ terminateSelf(): Promise&lt;void&gt;;
``` ```
## ServiceExtensionContext.connectAbility ## ServiceExtensionContext.connectAbility
connectAbility(want: Want, options: ConnectOptions): number; connectAbility(want: Want, options: ConnectOptions): number;
...@@ -174,7 +321,7 @@ connectAbility(want: Want, options: ConnectOptions): number; ...@@ -174,7 +321,7 @@ connectAbility(want: Want, options: ConnectOptions): number;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 | | want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 |
| options | [ConnectOptions](#connectoptions) | 是 | ConnectOptions类型的回调函数,返回服务连接成功、断开或连接失败后的信息。 | | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | 是 | ConnectOptions类型的回调函数,返回服务连接成功、断开或连接失败后的信息。 |
**返回值:** **返回值:**
...@@ -197,6 +344,47 @@ connectAbility(want: Want, options: ConnectOptions): number; ...@@ -197,6 +344,47 @@ connectAbility(want: Want, options: ConnectOptions): number;
let connection = this.context.connectAbility(want,options); let connection = this.context.connectAbility(want,options);
``` ```
## ServiceExtensionContext.connectAbilityWithAccount
connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number;
使用AbilityInfo.AbilityType.SERVICE模板和account将当前能力连接到一个能力。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
| accountId | number | 是 | 需要启动的accountId。 |
| options | ConnectOptions | 否 | 远端对象实例。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| number | 返回Ability连接的结果code。 |
**示例:**
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
};
var accountId = 100;
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') }
}
const result = this.context.connectAbilityWithAccount(want, accountId, options);
console.log('----------- connectAbilityResult: ------------', result);
```
## ServiceExtensionContext.disconnectAbility ## ServiceExtensionContext.disconnectAbility
...@@ -229,10 +417,8 @@ disconnectAbility(connection: number, callback:AsyncCallback&lt;void&gt;): void; ...@@ -229,10 +417,8 @@ disconnectAbility(connection: number, callback:AsyncCallback&lt;void&gt;): void;
} }
} }
``` ```
## ServiceExtensionContext.disconnectAbility ## ServiceExtensionContext.disconnectAbility
disconnectAbility(connection: number): Promise&lt;void&gt;; disconnectAbility(connection: number): Promise&lt;void&gt;;
...@@ -271,16 +457,3 @@ disconnectAbility(connection: number): Promise&lt;void&gt;; ...@@ -271,16 +457,3 @@ disconnectAbility(connection: number): Promise&lt;void&gt;;
} }
``` ```
\ No newline at end of file
## ConnectOptions
ConnectOptions数据结构。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 说明 |
| -------- | -------- |
| onConnect(elementName:ElementName,&nbsp;remote:IRemoteObject) | Ability成功连接一个服务类型Ability的回调接口。 |
| onDisconnect(elementName:ElementName) | 对端服务发生异常或者被杀死回调该接口。 |
| onFailed(code:&nbsp;number) | 连接失败时回调该接口。 |
# SIM卡管理 # SIM卡管理
SIM卡管理模块提供了SIM卡管理的基础能力,包括获取指定卡槽SIM卡的名称、号码、ISO国家码、归属PLMN号、服务提供商名称、SIM卡状态、卡类型、是否插卡、是否激活、锁状态,设置指定卡槽SIM卡显示的名称、号码、锁状态,激活、禁用指定卡槽SIM卡,更改Pin密码,以及解锁指定卡槽SIM卡密码、SIM卡密码的解锁密码等。
>**说明:** >**说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -509,7 +511,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback<IccAccountInfo\>): voi ...@@ -509,7 +511,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback<IccAccountInfo\>): voi
获取SIM卡账户信息,使用callback方式作为异步方法。 获取SIM卡账户信息,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -520,7 +522,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback<IccAccountInfo\>): voi ...@@ -520,7 +522,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback<IccAccountInfo\>): voi
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | -------------------------------------- | | -------- | --------------------------------------------------- | ---- | -------------------------------------- |
| slotId | number | 是 | 卡槽ID。<br/>- 0:卡槽1<br/>- 1:卡槽2 | | slotId | number | 是 | 卡槽ID。<br/>- 0:卡槽1<br/>- 1:卡槽2 |
| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | 是 | 回调函数。参考[IccAccountInfo](#IccAccountInfo7) | | callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | 是 | 回调函数。 |
**示例:** **示例:**
...@@ -537,7 +539,7 @@ getSimAccountInfo(slotId: number): Promise<IccAccountInfo\> ...@@ -537,7 +539,7 @@ getSimAccountInfo(slotId: number): Promise<IccAccountInfo\>
获取SIM卡账户信息,使用callback方式作为异步方法。 获取SIM卡账户信息,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -572,7 +574,7 @@ getActiveSimAccountInfoList(callback: AsyncCallback<Array<IccAccountInfo\>>): vo ...@@ -572,7 +574,7 @@ getActiveSimAccountInfoList(callback: AsyncCallback<Array<IccAccountInfo\>>): vo
获取活跃SIM卡账户信息列表,使用callback方式作为异步方法。 获取活跃SIM卡账户信息列表,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -599,7 +601,7 @@ getActiveSimAccountInfoList(): Promise<Array<IccAccountInfo\>>; ...@@ -599,7 +601,7 @@ getActiveSimAccountInfoList(): Promise<Array<IccAccountInfo\>>;
获取活跃SIM卡账户信息列表,使用callback方式作为异步方法。 获取活跃SIM卡账户信息列表,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -628,7 +630,7 @@ setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback<void\>): void ...@@ -628,7 +630,7 @@ setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback<void\>): void
设置默认语音业务的卡槽ID,使用callback方式作为异步方法。 设置默认语音业务的卡槽ID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -656,7 +658,7 @@ setDefaultVoiceSlotId(slotId: number): Promise\<void\> ...@@ -656,7 +658,7 @@ setDefaultVoiceSlotId(slotId: number): Promise\<void\>
设置默认语音业务的卡槽ID,使用Promise方式作为异步方法。 设置默认语音业务的卡槽ID,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -671,8 +673,8 @@ setDefaultVoiceSlotId(slotId: number): Promise\<void\> ...@@ -671,8 +673,8 @@ setDefaultVoiceSlotId(slotId: number): Promise\<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -691,7 +693,7 @@ setShowName\(slotId: number, name: string,callback: AsyncCallback<void\>\): void ...@@ -691,7 +693,7 @@ setShowName\(slotId: number, name: string,callback: AsyncCallback<void\>\): void
设置指定卡槽SIM卡显示的名称,使用callback方式作为异步方法。 设置指定卡槽SIM卡显示的名称,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -720,7 +722,7 @@ setShowName\(slotId: number, name: string\): Promise\<void\> ...@@ -720,7 +722,7 @@ setShowName\(slotId: number, name: string\): Promise\<void\>
设置指定卡槽SIM卡显示的名称,使用Promise方式作为异步方法。 设置指定卡槽SIM卡显示的名称,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -736,8 +738,8 @@ setShowName\(slotId: number, name: string\): Promise\<void\> ...@@ -736,8 +738,8 @@ setShowName\(slotId: number, name: string\): Promise\<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -757,7 +759,7 @@ getShowName(slotId: number, callback: AsyncCallback<string\>): void ...@@ -757,7 +759,7 @@ getShowName(slotId: number, callback: AsyncCallback<string\>): void
获取指定卡槽SIM卡的名称,使用callback方式作为异步方法。 获取指定卡槽SIM卡的名称,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -785,7 +787,7 @@ getShowName(slotId: number): Promise<string\> ...@@ -785,7 +787,7 @@ getShowName(slotId: number): Promise<string\>
获取指定卡槽SIM卡的名称,使用Promise方式作为异步方法。 获取指定卡槽SIM卡的名称,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -820,7 +822,7 @@ setShowNumber\(slotId: number, number: string,callback: AsyncCallback<void\>\): ...@@ -820,7 +822,7 @@ setShowNumber\(slotId: number, number: string,callback: AsyncCallback<void\>\):
设置指定卡槽SIM卡的号码,使用callback方式作为异步方法。 设置指定卡槽SIM卡的号码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -850,7 +852,7 @@ setShowNumber\(slotId: number,number: string\): Promise\<void\> ...@@ -850,7 +852,7 @@ setShowNumber\(slotId: number,number: string\): Promise\<void\>
设置指定卡槽SIM卡的号码,使用Promise方式作为异步方法。 设置指定卡槽SIM卡的号码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -867,7 +869,7 @@ setShowNumber\(slotId: number,number: string\): Promise\<void\> ...@@ -867,7 +869,7 @@ setShowNumber\(slotId: number,number: string\): Promise\<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | -------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -887,7 +889,7 @@ getShowNumber(slotId: number,callback: AsyncCallback<string\>): void ...@@ -887,7 +889,7 @@ getShowNumber(slotId: number,callback: AsyncCallback<string\>): void
获取指定卡槽SIM卡的号码,使用callback方式作为异步方法。 获取指定卡槽SIM卡的号码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -915,7 +917,7 @@ getShowNumber(slotId: number): Promise<string\> ...@@ -915,7 +917,7 @@ getShowNumber(slotId: number): Promise<string\>
获取指定卡槽SIM卡的号码,使用Promise方式作为异步方法。 获取指定卡槽SIM卡的号码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE **需要权限**:ohos.permission.GET_TELEPHONY_STATE
...@@ -950,7 +952,7 @@ activateSim(slotId: number, callback: AsyncCallback<void\>): void ...@@ -950,7 +952,7 @@ activateSim(slotId: number, callback: AsyncCallback<void\>): void
激活指定卡槽SIM卡,使用callback方式作为异步方法。 激活指定卡槽SIM卡,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -978,7 +980,7 @@ activateSim(slotId: number): Promise\<void\> ...@@ -978,7 +980,7 @@ activateSim(slotId: number): Promise\<void\>
激活指定卡槽SIM卡,使用Promise方式作为异步方法。 激活指定卡槽SIM卡,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -993,8 +995,8 @@ activateSim(slotId: number): Promise\<void\> ...@@ -993,8 +995,8 @@ activateSim(slotId: number): Promise\<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -1013,7 +1015,7 @@ deactivateSim(slotId: number, callback: AsyncCallback<void\>): void ...@@ -1013,7 +1015,7 @@ deactivateSim(slotId: number, callback: AsyncCallback<void\>): void
禁用指定卡槽SIM卡,使用callback方式作为异步方法。 禁用指定卡槽SIM卡,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1041,7 +1043,7 @@ deactivateSim(slotId: number): Promise\<void\> ...@@ -1041,7 +1043,7 @@ deactivateSim(slotId: number): Promise\<void\>
禁用指定卡槽SIM卡,使用Promise方式作为异步方法。 禁用指定卡槽SIM卡,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1056,8 +1058,8 @@ deactivateSim(slotId: number): Promise\<void\> ...@@ -1056,8 +1058,8 @@ deactivateSim(slotId: number): Promise\<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -1076,7 +1078,7 @@ setLockState(slotId: number, options: LockInfo, callback: AsyncCallback<LockStat ...@@ -1076,7 +1078,7 @@ setLockState(slotId: number, options: LockInfo, callback: AsyncCallback<LockStat
设置指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。 设置指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1108,7 +1110,7 @@ setLockState(slotId: number, options: LockInfo): Promise<LockStatusResponse\> ...@@ -1108,7 +1110,7 @@ setLockState(slotId: number, options: LockInfo): Promise<LockStatusResponse\>
设置指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。 设置指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1147,7 +1149,7 @@ getLockState(slotId: number, lockType: LockType, callback: AsyncCallback<LockSta ...@@ -1147,7 +1149,7 @@ getLockState(slotId: number, lockType: LockType, callback: AsyncCallback<LockSta
获取指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。 获取指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService **系统能力**:SystemCapability.Telephony.CoreService
...@@ -1174,7 +1176,7 @@ getLockState(slotId: number, lockType: LockType): Promise<LockState\> ...@@ -1174,7 +1176,7 @@ getLockState(slotId: number, lockType: LockType): Promise<LockState\>
获取指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。 获取指定卡槽SIM卡的锁状态,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService **系统能力**:SystemCapability.Telephony.CoreService
...@@ -1208,7 +1210,7 @@ alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback ...@@ -1208,7 +1210,7 @@ alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback
更改Pin密码,使用callback方式作为异步方法。 更改Pin密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1238,7 +1240,7 @@ alterPin(slotId: number, newPin: string, oldPin: string): Promise<LockStatusResp ...@@ -1238,7 +1240,7 @@ alterPin(slotId: number, newPin: string, oldPin: string): Promise<LockStatusResp
更改Pin密码,使用callback方式作为异步方法。 更改Pin密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1275,7 +1277,7 @@ alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallb ...@@ -1275,7 +1277,7 @@ alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallb
更改Pin2密码,使用callback方式作为异步方法。 更改Pin2密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1305,7 +1307,7 @@ alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise<LockStatusR ...@@ -1305,7 +1307,7 @@ alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise<LockStatusR
更改Pin2密码,使用callback方式作为异步方法。 更改Pin2密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1342,7 +1344,7 @@ unlockPin(slotId: number,pin: string ,callback: AsyncCallback<LockStatusResponse ...@@ -1342,7 +1344,7 @@ unlockPin(slotId: number,pin: string ,callback: AsyncCallback<LockStatusResponse
解锁指定卡槽SIM卡密码,使用callback方式作为异步方法。 解锁指定卡槽SIM卡密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1372,7 +1374,7 @@ unlockPin(slotId: number,pin: string): Promise&lt;LockStatusResponse\> ...@@ -1372,7 +1374,7 @@ unlockPin(slotId: number,pin: string): Promise&lt;LockStatusResponse\>
解锁指定卡槽SIM卡密码,使用Promise方式作为异步方法。 解锁指定卡槽SIM卡密码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1409,7 +1411,7 @@ unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback<Loc ...@@ -1409,7 +1411,7 @@ unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback<Loc
解锁指定卡槽SIM卡密码的解锁密码,使用callback方式作为异步方法。 解锁指定卡槽SIM卡密码的解锁密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1441,7 +1443,7 @@ unlockPuk(slotId: number,newPin: string,puk: string): Promise&lt;LockStatusRespo ...@@ -1441,7 +1443,7 @@ unlockPuk(slotId: number,newPin: string,puk: string): Promise&lt;LockStatusRespo
解锁指定卡槽SIM卡密码的解锁密码,使用Promise方式作为异步方法。 解锁指定卡槽SIM卡密码的解锁密码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1480,7 +1482,7 @@ promise.then(data => { ...@@ -1480,7 +1482,7 @@ promise.then(data => {
解锁指定卡槽SIM卡密码,使用callback方式作为异步方法。 解锁指定卡槽SIM卡密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1510,7 +1512,7 @@ unlockPin2(slotId: number,pin2: string): Promise&lt;LockStatusResponse\> ...@@ -1510,7 +1512,7 @@ unlockPin2(slotId: number,pin2: string): Promise&lt;LockStatusResponse\>
解锁指定卡槽SIM卡密码,使用Promise方式作为异步方法。 解锁指定卡槽SIM卡密码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1547,7 +1549,7 @@ unlockPuk2(slotId: number,newPin2: string,puk2: string ,callback: AsyncCallback< ...@@ -1547,7 +1549,7 @@ unlockPuk2(slotId: number,newPin2: string,puk2: string ,callback: AsyncCallback<
解锁指定卡槽SIM卡密码的解锁密码,使用callback方式作为异步方法。 解锁指定卡槽SIM卡密码的解锁密码,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1579,7 +1581,7 @@ unlockPuk2slotId: number,newPin2: string,puk2: string): Promise&lt;LockStatusRes ...@@ -1579,7 +1581,7 @@ unlockPuk2slotId: number,newPin2: string,puk2: string): Promise&lt;LockStatusRes
解锁指定卡槽SIM卡密码的解锁密码,使用Promise方式作为异步方法。 解锁指定卡槽SIM卡密码的解锁密码,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -1671,7 +1673,7 @@ SIM卡状态。 ...@@ -1671,7 +1673,7 @@ SIM卡状态。
锁类型。 锁类型。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1684,7 +1686,7 @@ SIM卡状态。 ...@@ -1684,7 +1686,7 @@ SIM卡状态。
锁状态。 锁状态。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1697,7 +1699,7 @@ SIM卡状态。 ...@@ -1697,7 +1699,7 @@ SIM卡状态。
定制锁类型。 定制锁类型。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1718,7 +1720,7 @@ SIM卡状态。 ...@@ -1718,7 +1720,7 @@ SIM卡状态。
锁状态响应。 锁状态响应。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1731,7 +1733,7 @@ SIM卡状态。 ...@@ -1731,7 +1733,7 @@ SIM卡状态。
锁状态响应。 锁状态响应。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1745,7 +1747,7 @@ SIM卡状态。 ...@@ -1745,7 +1747,7 @@ SIM卡状态。
锁状态响应。 锁状态响应。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
...@@ -1758,7 +1760,7 @@ SIM卡状态。 ...@@ -1758,7 +1760,7 @@ SIM卡状态。
Icc账户信息。 Icc账户信息。
接口为系统接口。 接口为系统接口。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Telephony.CoreService。
......
# 短信服务 # 短信服务
短信服务提供了管理短信的一些基础能力,包括创建、发送短信,获取、设置发送短信的默认SIM卡槽ID,获取、设置短信服务中心(SMSC)地址,以及检查当前设备是否具备短信发送和接收能力等。
>**说明:** >**说明:**
> >
>本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -162,7 +164,7 @@ setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback&lt;void&gt;\): void ...@@ -162,7 +164,7 @@ setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback&lt;void&gt;\): void
设置发送短信的默认SIM卡槽ID,使用callback方式作为异步方法。 设置发送短信的默认SIM卡槽ID,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -190,7 +192,7 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt; ...@@ -190,7 +192,7 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt;
设置发送短信的默认SIM卡槽ID,使用Promise方式作为异步方法。 设置发送短信的默认SIM卡槽ID,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -205,8 +207,8 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt; ...@@ -205,8 +207,8 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt;
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
...@@ -225,7 +227,7 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback<void\>\): ...@@ -225,7 +227,7 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback<void\>\):
设置短信服务中心(SMSC)地址,使用callback方式作为异步方法。 设置短信服务中心(SMSC)地址,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限 **需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限
...@@ -256,7 +258,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\<void\> ...@@ -256,7 +258,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\<void\>
设置短信服务中心(SMSC)地址,使用Promise方式作为异步方法。 设置短信服务中心(SMSC)地址,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限 **需要权限**:ohos.permission.SET_TELEPHONY_STATE,该权限为系统权限
...@@ -295,7 +297,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback<string\>\): void ...@@ -295,7 +297,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback<string\>\): void
获取短信服务中心(SMSC)地址,使用callback方式作为异步方法。 获取短信服务中心(SMSC)地址,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限 **需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限
...@@ -324,7 +326,7 @@ getSmscAddr\(slotId: number\): Promise<string\> ...@@ -324,7 +326,7 @@ getSmscAddr\(slotId: number\): Promise<string\>
获取短信服务中心(SMSC)地址,使用Promise方式作为异步方法。 获取短信服务中心(SMSC)地址,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限 **需要权限**:ohos.permission.GET_TELEPHONY_STATE,该权限为系统权限
......
# 蜂窝数据 # 蜂窝数据
蜂窝数据提供了移动数据管理能力,包括获取、设置默认移动数据的SIM卡,获取蜂窝数据业务的上下行和分组交换域(PS域)的连接状态,以及检查蜂窝数据业务和漫游是否启用等。
>**说明:** >**说明:**
> >
>本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 >本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -67,7 +69,7 @@ setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): vo ...@@ -67,7 +69,7 @@ setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): vo
设置默认移动数据的SIM卡,使用callback方式作为异步方法。 设置默认移动数据的SIM卡,使用callback方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -78,7 +80,7 @@ setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): vo ...@@ -78,7 +80,7 @@ setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): vo
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------- | ---- | ------------------------------------------------------------ |
| slotId | number | 是 | SIM卡槽ID。<br/>- 0:卡槽1。<br/>- 1:卡槽2。<br/>- -1:清除默认配置。 | | slotId | number | 是 | SIM卡槽ID。<br/>- 0:卡槽1。<br/>- 1:卡槽2。<br/>- -1:清除默认配置。 |
| callback | AsyncCallback\<void\> | 是 | 回调函数。当设置成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback\<void\> | 是 | 回调函数。 |
**示例:** **示例:**
...@@ -94,7 +96,7 @@ setDefaultCellularDataSlotId(slotId: number): Promise\<void\> ...@@ -94,7 +96,7 @@ setDefaultCellularDataSlotId(slotId: number): Promise\<void\>
设置默认移动数据的SIM卡,使用Promise方式作为异步方法。 设置默认移动数据的SIM卡,使用Promise方式作为异步方法。
接口为系统接口。 接口为系统接口。
**需要权限**:ohos.permission.SET_TELEPHONY_STATE **需要权限**:ohos.permission.SET_TELEPHONY_STATE
...@@ -109,8 +111,8 @@ setDefaultCellularDataSlotId(slotId: number): Promise\<void\> ...@@ -109,8 +111,8 @@ setDefaultCellularDataSlotId(slotId: number): Promise\<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise<\void\> | 无返回结果的Promise对象。 | | Promise\<void\> | 以Promise形式异步返回设置结果。 |
**示例:** **示例:**
......
...@@ -14,8 +14,6 @@ TestRunner模块提供了框架测试的能力。包括准备单元测试环境 ...@@ -14,8 +14,6 @@ TestRunner模块提供了框架测试的能力。包括准备单元测试环境
import TestRunner from '@ohos.application.testRunner' import TestRunner from '@ohos.application.testRunner'
``` ```
## TestRunner.onPrepare ## TestRunner.onPrepare
onPrepare(): void onPrepare(): void
......
# 用户界面外观
用户界面外观提供管理系统外观的一些基础能力,目前仅包括深浅色模式配置。
> **说明:**
> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 本模块接口为系统接口。
## 导入模块
```ts
import uiAppearance from '@ohos.uiAppearance'
```
## DarkMode
深色模式枚举。
| 名称 | 值 | 说明 |
| -- | -- | -- |
| ALWAYS_DARK | 0 | 系统始终为深色。 |
| ALWAYS_LIGHT | 1 | 系统始终为浅色。 |
## uiAppearance.setDarkMode
setDarkMode(mode: DarkMode, callback: AsyncCallback\<void>): void
设置系统深色模式。
**需要权限:** ohos.permission.UPDATE_CONFIGRATION
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | 是 | 指定系统的深色模式配置 |
| callback | AsyncCallback\<void>| 是 | 配置深色模式的异步回调 |
**示例:**
```ts
uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK, (err) => {
console.info(`${err}`);
})
```
## uiAppearance.setDarkMode
setDarkMode(mode: DarkMode): Promise\<void>;
设置系统深色模式。
**需要权限:** ohos.permission.UPDATE_CONFIGRATION
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | 是 | 指定系统深色模式配置 |
**示例:**
```ts
uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK).then(() => {
console.log('Set dark-mode successfully.');
}).catch((err) => {
console.log(`Set dark-mode failed, ${err}`);
});
```
## uiAppearance.getDarkMode
getDarkMode(): DarkMode;
获取当前的深色模式配置。
**需要权限:** ohos.permission.UPDATE_CONFIGRATION
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| -- | -- |
|[DarkMode](#darkmode) | 系统当前的深色模式配置 |
**示例:**
```ts
let darkMode = uiAppearance.getDarkMode();
console.log(`Get dark-mode ${darkMode}`);
```
\ No newline at end of file
...@@ -408,8 +408,6 @@ UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属 ...@@ -408,8 +408,6 @@ UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属
坐标点信息。 坐标点信息。
**系统能力**:SystemCapability.Test.UiTest
| 名称 | 参数类型 | 可读 | 可写 | 描述 | | 名称 | 参数类型 | 可读 | 可写 | 描述 |
| ---- | -------- | ---- | ---- | ---------------- | | ---- | -------- | ---- | ---- | ---------------- |
| X | number | 是 | 否 | 坐标点的横坐标。 | | X | number | 是 | 否 | 坐标点的横坐标。 |
...@@ -419,8 +417,6 @@ UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属 ...@@ -419,8 +417,6 @@ UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属
控件的边框信息。 控件的边框信息。
**系统能力**:SystemCapability.Test.UiTest
| 名称 | 参数类型 | 可读 | 可写 | 描述 | | 名称 | 参数类型 | 可读 | 可写 | 描述 |
| ------- | -------- | ---- | ---- | ------------------------- | | ------- | -------- | ---- | ---- | ------------------------- |
| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | | leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 |
...@@ -1775,8 +1771,6 @@ async function demo() { ...@@ -1775,8 +1771,6 @@ async function demo() {
窗口调整大小的方向。 窗口调整大小的方向。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Test.UiTest
| 名称 | 说明 | | 名称 | 说明 |
| ---------- | -------- | | ---------- | -------- |
| LEFT | 左方。 | | LEFT | 左方。 |
...@@ -1792,8 +1786,6 @@ async function demo() { ...@@ -1792,8 +1786,6 @@ async function demo() {
窗口的窗口模式。 窗口的窗口模式。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Test.UiTest
| 名称 | 说明 | | 名称 | 说明 |
| ---------- | ---------- | | ---------- | ---------- |
| FULLSCREEN | 全屏模式。 | | FULLSCREEN | 全屏模式。 |
......
...@@ -6,15 +6,12 @@ uriPermissionManager模块提供了Uri权限管理的能力。 ...@@ -6,15 +6,12 @@ uriPermissionManager模块提供了Uri权限管理的能力。
> >
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
``` ```
import UriPermissionManager from '@ohos.application.uriPermissionManager'; import UriPermissionManager from '@ohos.application.uriPermissionManager';
``` ```
## uriPermissionManager.verifyUriPermission ## uriPermissionManager.verifyUriPermission
verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void
......
# webgl # WebGL
> **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
WebGL提供图形绘制的能力,包括对当前绘制图形的位置、颜色等进行处理。
WebGL标准图形API,对应OpenGL ES 2.0特性集。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/1.0/) WebGL标准图形API,对应OpenGL ES 2.0特性集。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/1.0/)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 调用方式 ## 调用方式
......
# webgl2 # WebGL2
> **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
WebGL2支持图形的绘制,包括对当前绘制图形的位置、颜色等进行处理,其中相对WebGL来说对渲染管道和着色语言进行了增强。
WebGL标准图形API,对应OpenGL ES 3.0特性集。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/2.0/) WebGL标准图形API,对应OpenGL ES 3.0特性集。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/2.0/)
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 调用方式 ## 调用方式
......
# Zip模块(JS端SDK接口) # Zip模块(JS端SDK接口)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 使用限制 ## 使用限制
...@@ -124,9 +125,9 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ...@@ -124,9 +125,9 @@ zlib.unzipFile(inFile, outFile, options).then((data) => {
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------- | ---- | --------------------------------------------------------- | | -------- | ---------------- | ---- | --------------------------------------------------------- |
| level | CompressLeve | 否 | [参考zip.CompressLevel枚举定义](#zip.CompressLevel) | | level | CompressLeve | 否 | 参考[zip.CompressLevel枚举定义](#zipcompresslevel) |
| memLevel | MemLevel | 否 | [参考zip.MemLevel枚举定义](#zip.MemLevel) | | memLevel | MemLevel | 否 | 参考[zip.MemLevel枚举定义](#zipmemlevel) |
| strategy | CompressStrategy | 否 | [参考zip.CompressStrategy枚举定义](#zip.CompressStrategy) | | strategy | CompressStrategy | 否 | 参考[zip.CompressStrategy枚举定义](#zipcompressstrategy) |
## zip.MemLevel ## zip.MemLevel
......
...@@ -37,16 +37,7 @@ Grid() ...@@ -37,16 +37,7 @@ Grid()
| minCount<font color=ff0000><sup>8+</sup></font> | number | 1 | 当layoutDirection是Row时,表示可显示的最小行数<br/>当layoutDirection是Column时,表示可显示的最小列数。 | | minCount<font color=ff0000><sup>8+</sup></font> | number | 1 | 当layoutDirection是Row时,表示可显示的最小行数<br/>当layoutDirection是Column时,表示可显示的最小列数。 |
| cellLength<font color=ff0000><sup>8+</sup></font> | number | 0 | 当layoutDirection是Row时,表示一行的高度<br/>当layoutDirection是Column时,表示一列的宽度。 | | cellLength<font color=ff0000><sup>8+</sup></font> | number | 0 | 当layoutDirection是Row时,表示一行的高度<br/>当layoutDirection是Column时,表示一列的宽度。 |
| multiSelectable<font color=ff0000><sup>8+</sup></font> | boolean | false | 是否开启鼠标框选。<br/>-&nbsp;false:关闭框选。<br/>-&nbsp;true:开启框选。 | | multiSelectable<font color=ff0000><sup>8+</sup></font> | boolean | false | 是否开启鼠标框选。<br/>-&nbsp;false:关闭框选。<br/>-&nbsp;true:开启框选。 |
| dragAnimation<font color=ff0000><sup>8+</sup></font> | boolean | false | 是否开启拖拽GridItem动画。 | | supportAnimation<font color=ff0000><sup>8+</sup></font> | boolean | false | 控制Grid是否支持动画。 |
| edgeEffection<font color=ff0000><sup>8+</sup></font> | EdgeEffect | EdgeEffect.Spring | 设置边缘滑动效果,目前支持的滑动效果参见EdgeEffect枚举说明。 |
- EdgeEffect枚举说明
| 名称 | 描述 |
| -------- | -------- |
| Spring | 弹性物理动效,滑动到边缘后可以根据初始速度或通过触摸事件继续滑动一段距离,松手后回弹。 |
| None | 滑动到边缘后无效果。 |
## 事件 ## 事件
......
...@@ -63,6 +63,7 @@ List(value:{space?: number, initialIndex?: number}) ...@@ -63,6 +63,7 @@ List(value:{space?: number, initialIndex?: number})
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------- | -------- | | -------- | -------- |
| onItemDelete(index:&nbsp;number)&nbsp;=&gt;&nbsp;boolean | 列表项删除时触发。 | | onItemDelete(index:&nbsp;number)&nbsp;=&gt;&nbsp;boolean | 列表项删除时触发。 |
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | 滚动开始事件回调。<br>参数:<br>- dx:即将发生的水平方向滚动量。<br>- dy:即将发生的竖向方向滚动量。<br>返回值:<br>- dxRemain:水平方向滚动剩余量。<br>- dyRemain:竖直方向滚动剩余量。 |
| onScrollIndex(firstIndex:&nbsp;number,&nbsp;lastIndex:&nbsp;number)&nbsp;=&gt;&nbsp;void | 当前列表显示的起始位置和终止位置发生变化时触发。 | | onScrollIndex(firstIndex:&nbsp;number,&nbsp;lastIndex:&nbsp;number)&nbsp;=&gt;&nbsp;void | 当前列表显示的起始位置和终止位置发生变化时触发。 |
> **说明:** > **说明:**
......
...@@ -9,14 +9,14 @@ ...@@ -9,14 +9,14 @@
## 规则说明 ## 规则说明
* 容器内子组件区分水平方向,垂直方向: * 容器内子组件区分水平方向,垂直方向
* 水平方向为left, middle, right,对应容器的HorizontalAlign.Start, HorizontalAlign.Center, HorizontalAlign.End * 水平方向为left, middle, right,对应容器的HorizontalAlign.Start, HorizontalAlign.Center, HorizontalAlign.End
* 垂直方向为top, center, bottom, right,对应容器的VerticalAlign.Top, VerticalAlign.Center, VerticalAlign.Bottom * 垂直方向为top, center, bottom,对应容器的VerticalAlign.Top, VerticalAlign.Center, VerticalAlign.Bottom
* 子组件可以将容器或者其他子组件设为锚点: * 子组件可以将容器或者其他子组件设为锚点
* 参与相对布局的容器内组件必须设置id,容器id固定为__container__ * 参与相对布局的容器内组件必须设置id,容器id固定为__container__
* 无id的子组件位置设置默认为容器左上方 * 无id的子组件位置设置默认为容器左上方
* 此子组件某一方向上的三个位置可以将容器或其他子组件的同方向三个位置为锚点,同方向上两个以上位置设置锚点以后会跳过第三个 * 此子组件某一方向上的三个位置可以将容器或其他子组件的同方向三个位置为锚点,同方向上两个以上位置设置锚点以后会跳过第三个
* 同方向上两个以上位置设置锚点时此子组件额外设置width, height不生效 * 同方向上两个以上位置设置锚点时此子组件额外设置widthheight不生效
* 对齐后需要额外偏移可设置offset * 对齐后需要额外偏移可设置offset
* 特殊情况 * 特殊情况
* 互相依赖,环形依赖时容器内子组件全部不绘制 * 互相依赖,环形依赖时容器内子组件全部不绘制
......
...@@ -42,10 +42,14 @@ Scroll(scroller?: Scroller) ...@@ -42,10 +42,14 @@ Scroll(scroller?: Scroller)
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ----------------------------- | | ---------------------------------------- | ----------------------------- |
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | 滚动开始事件回调。<br>参数:<br>- dx:即将发生的水平方向滚动量。<br>- dy:即将发生的竖向方向滚动量。<br>返回值:<br>- dxRemain:水平方向滚动剩余量。<br>- dyRemain:竖直方向滚动剩余量。 |
| onScroll(xOffset:&nbsp;number,&nbsp;yOffset:&nbsp;number)&nbsp;=&gt;&nbsp;void | 滚动事件回调,&nbsp;返回滚动时水平、竖直方向偏移量。 | | onScroll(xOffset:&nbsp;number,&nbsp;yOffset:&nbsp;number)&nbsp;=&gt;&nbsp;void | 滚动事件回调,&nbsp;返回滚动时水平、竖直方向偏移量。 |
| onScrollEdge(side:&nbsp;Edge)&nbsp;=&gt;&nbsp;void | 滚动到边缘事件回调。 | | onScrollEdge(side:&nbsp;Edge)&nbsp;=&gt;&nbsp;void | 滚动到边缘事件回调。 |
| onScrollEnd()&nbsp;=&gt;&nbsp;void | 滚动停止事件回调。 | | onScrollEnd()&nbsp;=&gt;&nbsp;void | 滚动停止事件回调。 |
> **说明:**
> 若通过onScrollBegin事件和scrollBy方法实现容器嵌套滚动,需设置子滚动节点的EdgeEffect为None。如Scroll嵌套List滚动时,List组件的edgeEffect属性需设置为EdgeEffect.None。
## Scroller ## Scroller
可滚动容器组件的控制器,可以将此组件绑定至容器组件,然后通过它控制容器组件的滚动,目前支持绑定到List和Scroll组件上。 可滚动容器组件的控制器,可以将此组件绑定至容器组件,然后通过它控制容器组件的滚动,目前支持绑定到List和Scroll组件上。
...@@ -103,7 +107,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void ...@@ -103,7 +107,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void
### currentOffset ### currentOffset
scroller.currentOffset(): Object currentOffset(): Object
返回当前的滚动偏移量。 返回当前的滚动偏移量。
...@@ -117,7 +121,7 @@ scroller.currentOffset(): Object ...@@ -117,7 +121,7 @@ scroller.currentOffset(): Object
### scrollToIndex ### scrollToIndex
scroller.scrollToIndex(value: number): void scrollToIndex(value: number): void
滑动到指定Index。 滑动到指定Index。
...@@ -133,6 +137,25 @@ scroller.scrollToIndex(value: number): void ...@@ -133,6 +137,25 @@ scroller.scrollToIndex(value: number): void
| value | number | 是 | - | 要滑动到的列表项在列表中的索引值。 | | value | number | 是 | - | 要滑动到的列表项在列表中的索引值。 |
### scrollBy
scrollBy(dx: Length, dy: Length): void
滑动指定距离。
> **说明:**
> 仅支持Scroll组件。
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ----- | ------ | ---- | ---- | ----------------- |
| dx | Length | 是 | - | 水平方向滚动距离。 |
| dy | Length | 是 | - | 竖直方向滚动距离。 |
## 示例 ## 示例
```ts ```ts
...@@ -188,3 +211,58 @@ struct ScrollExample { ...@@ -188,3 +211,58 @@ struct ScrollExample {
``` ```
![zh-cn_image_0000001174104386](figures/zh-cn_image_0000001174104386.gif) ![zh-cn_image_0000001174104386](figures/zh-cn_image_0000001174104386.gif)
```ts
@Entry
@Component
struct NestedScroll {
@State listPosition: number = 0 // 0代表滚动到List顶部,1代表中间值,2代表滚动到List底部。
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller()
build() {
Flex() {
Scroll(this.scroller) {
Column() {
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
List({ space: 20 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text("ListItem" + item)
.width("100%").height("100%").borderRadius(15)
.fontSize(16).textAlign(TextAlign.Center).backgroundColor(Color.White)
}.width("100%").height(100)
}, item => item)
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
})
.onReachEnd(() => {
this.listPosition = 2
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
}
this.listPosition = 1;
return { dxRemain: dx, dyRemain: dy }
})
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
}
}
.width("100%").height("100%")
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20)
}
}
```
![NestedScroll](figures/NestedScroll.gif)
\ No newline at end of file
...@@ -43,7 +43,6 @@ struct DragExample { ...@@ -43,7 +43,6 @@ struct DragExample {
@State orangeVisible: Visibility = Visibility.Visible @State orangeVisible: Visibility = Visibility.Visible
@State bananaVisible: Visibility = Visibility.Visible @State bananaVisible: Visibility = Visibility.Visible
@State select: number = 0 @State select: number = 0
@State currentIndex: number = 0
@Builder pixelMapBuilder() { @Builder pixelMapBuilder() {
Column() { Column() {
......
...@@ -136,3 +136,4 @@ ...@@ -136,3 +136,4 @@
| ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | 允许应用设置、重置默认应用。 | | ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | 允许应用设置、重置默认应用。 |
| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | 允许设置和查询应用的处置状态。 | | ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | 允许设置和查询应用的处置状态。 |
| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | 允许应用查询设备的唯一标识符信息。 | | ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | 允许应用查询设备的唯一标识符信息。 |
| ohos.permission.DUMP | system_core | system_grant | TRUE | 允许导出系统基础信息和SA服务信息。 |
\ No newline at end of file
...@@ -12,13 +12,13 @@ Ability: 一个应用程序可以拥有多个Ability,一个Ability中的所 ...@@ -12,13 +12,13 @@ Ability: 一个应用程序可以拥有多个Ability,一个Ability中的所
## @LocalStorageLink装饰器 ## @LocalStorageLink装饰器
组件通过使用@LocalStorageLink(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立双向数据绑定当创建包含@LocalStorageLink的状态变量的组件时,该状态变量的值将会使用LocalStorage中的值进行初始化。如果LocalStorage中未定义初始值,将使用@LocalStorageLink定义的初始值。在UI组件中对@LocalStorageLink的状态变量所做的更改将同步到LocalStorage中,并从LocalStorage同步到Ability下的组件中。 组件通过使用@LocalStorageLink(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立双向数据绑定当创建包含@LocalStorageLink的状态变量的组件时,该状态变量的值将会使用LocalStorage中的值进行初始化。如果LocalStorage中未定义初始值,将使用@LocalStorageLink定义的初始值。在UI组件中对@LocalStorageLink的状态变量所做的更改将同步到LocalStorage中,并从LocalStorage同步到Ability下的组件中。
## @LocalStorageProp装饰器 ## @LocalStorageProp装饰器
组件通过使用LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定当创建包含@LocalStorageProp的状态变量的组件时,该状态变量的值将使用LocalStorage中的值进行初始化。LocalStorage中的属性值的更改会导致当前Ability下的所有UI组件进行状态更新。 组件通过使用LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定当创建包含@LocalStorageProp的状态变量的组件时,该状态变量的值将使用LocalStorage中的值进行初始化。LocalStorage中的属性值的更改会导致当前Ability下的所有UI组件进行状态更新。
> **说明:** 创建LocalStorage实例时没有给LocalStorage实例默认值时,可以使用组件内@LocalStorageLink和@LocalStorageProp的默认值,如果定义时给定了默认值,那么不会再使用@LocalStorageLink和@LocalStorageProp的默认值。 > **说明:** 创建LocalStorage实例时如未定义初始值,可以使用组件内@LocalStorageLink和@LocalStorageProp的初始值。如果定义时给定了初始值,那么不会再使用@LocalStorageLink和@LocalStorageProp的初始值。
## LocalStorage接口 ## LocalStorage接口
...@@ -58,7 +58,7 @@ has(propName: string): boolean ...@@ -58,7 +58,7 @@ has(propName: string): boolean
### get ### get
get<T>(propName: string): T get\<T>(propName: string): T
获取对应key值的value。 获取对应key值的value。
...@@ -78,7 +78,7 @@ get<T>(propName: string): T ...@@ -78,7 +78,7 @@ get<T>(propName: string): T
### set ### set
set<T>(propName: string, newValue: T): boolean set\<T>(propName: string, newValue: T): boolean
存储对象值。 存储对象值。
...@@ -99,7 +99,7 @@ get<T>(propName: string): T ...@@ -99,7 +99,7 @@ get<T>(propName: string): T
### setOrCreate ### setOrCreate
setOrCreate<T>(propName: string, newValue: T): boolean setOrCreate\<T>(propName: string, newValue: T): boolean
创建或更新setOrCreate内部的值。 创建或更新setOrCreate内部的值。
...@@ -120,7 +120,7 @@ get<T>(propName: string): T ...@@ -120,7 +120,7 @@ get<T>(propName: string): T
### link ### link
link<T>(propName: string): T link\<T>(propName: string): T
与localStorage双向数据绑定。 与localStorage双向数据绑定。
...@@ -140,7 +140,7 @@ get<T>(propName: string): T ...@@ -140,7 +140,7 @@ get<T>(propName: string): T
### setAndLink ### setAndLink
setAndLink<T>(propName: string, defaultValue: T): T setAndLink\<T>(propName: string, defaultValue: T): T
与link接口类似,双向数据绑定localStorage。 与link接口类似,双向数据绑定localStorage。
...@@ -161,7 +161,7 @@ get<T>(propName: string): T ...@@ -161,7 +161,7 @@ get<T>(propName: string): T
### prop ### prop
prop<T>(propName: string): T prop\<T>(propName: string): T
单向属性绑定的一种。更新组件的状态。 单向属性绑定的一种。更新组件的状态。
...@@ -181,7 +181,7 @@ prop<T>(propName: string): T ...@@ -181,7 +181,7 @@ prop<T>(propName: string): T
### setAndProp ### setAndProp
setAndProp<T>(propName: string, defaultValue: T): T setAndProp\<T>(propName: string, defaultValue: T): T
与Prop接口类似,存在localStorage的单向数据绑定prop值。 与Prop接口类似,存在localStorage的单向数据绑定prop值。
...@@ -190,7 +190,7 @@ setAndProp<T>(propName: string, defaultValue: T): T ...@@ -190,7 +190,7 @@ setAndProp<T>(propName: string, defaultValue: T): T
| 参数名 | 类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 类型 | 必填 | 默认值 | 参数描述 |
| ------------ | ------ | :--: | ------ | --------------------------- | | ------------ | ------ | :--: | ------ | --------------------------- |
| propName | string | 是 | - | 要保存的的键值对中的key值。 | | propName | string | 是 | - | 要保存的的键值对中的key值。 |
| defaultValue | S | 是 | - | 创建的默认值。 | | defaultValue | T | 是 | - | 创建的默认值。 |
**返回值:** **返回值:**
...@@ -222,7 +222,7 @@ delete(propName: string): boolean ...@@ -222,7 +222,7 @@ delete(propName: string): boolean
### keys ### keys
keys(): IterableIterator<string> keys(): IterableIterator\<string>
查找所有键。 查找所有键。
...@@ -230,7 +230,7 @@ keys(): IterableIterator<string> ...@@ -230,7 +230,7 @@ keys(): IterableIterator<string>
| 类型 | 描述 | | 类型 | 描述 |
| ------------- | ---------------------------- | | ------------- | ---------------------------- |
| array<string> | 返回包含所有键的字符串数组。 | | array\<string> | 返回包含所有键的字符串数组。 |
......
...@@ -12,17 +12,17 @@ WebGL主要帮助开发者在前端开发中完成图形图像的相关处理, ...@@ -12,17 +12,17 @@ WebGL主要帮助开发者在前端开发中完成图形图像的相关处理,
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| canvas.getContext | 获取canvas对象上下文。 | | canvas.getContext | 获取canvas对象上下文。 |
| webgl.createBuffer():&nbsp;WebGLBuffer&nbsp;\|&nbsp;null | 创建与初始化WebGL数据缓冲区。 | | webgl.createBuffer(): WebGLBuffer \| null | 创建与初始化WebGL数据缓冲区。 |
| webgl.bindBuffer(target:&nbsp;GLenum,<br />&nbsp;buffer:&nbsp;WebGLBuffer&nbsp;\|&nbsp;null):&nbsp;void | 将WebGL数据缓冲区与目标进行绑定。 | | webgl.bindBuffer(target: GLenum, buffer: WebGLBuffer \| null): void | 将WebGL数据缓冲区与目标进行绑定。 |
| webgl.bufferData(target:&nbsp;GLenum,&nbsp;srcData:&nbsp;ArrayBufferView,<br />&nbsp;usage:&nbsp;GLenum,&nbsp;srcOffset:&nbsp;GLuint,&nbsp;length?:&nbsp;GLuint):&nbsp;void | 创建并初始化WebGL的数据存储区。 | | webgl.bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint): void | 创建并初始化WebGL的数据存储区。 |
| webgl.getAttribLocation(program:&nbsp;WebGLProgram,<br />&nbsp;name:&nbsp;string):&nbsp;GLint | 从给定WebGL着色程序中获取着色器中attribute变量的地址。 | | webgl.getAttribLocation(program: WebGLProgram, name: string): GLint | 从给定WebGL着色程序中获取着色器中attribute变量的地址。 |
| webgl.vertexAttribPointer(index:&nbsp;GLuint,&nbsp;size:&nbsp;GLint,&nbsp;type:&nbsp;GLenum,<br />&nbsp;normalized:&nbsp;GLboolean,&nbsp;stride:&nbsp;GLsizei,&nbsp;offset:&nbsp;GLintptr):&nbsp;void | 将缓冲区对象分配给变量。 | | webgl.vertexAttribPointer(index GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr): void | 将缓冲区对象分配给变量。 |
| webgl.enableVertexAttribArray(index:&nbsp;GLuint):&nbsp;void | 连接变量与分配给它的缓冲区对象。 | | webgl.enableVertexAttribArray(index: GLuint): void | 连接变量与分配给它的缓冲区对象。 |
| webgl.clearColor(red:&nbsp;GLclampf,&nbsp;green:&nbsp;GLclampf,<br />&nbsp;blue:&nbsp;GLclampf,&nbsp;alpha:&nbsp;GLclampf):&nbsp;void | 清空&lt;canvas&gt;指定的颜色。 | | webgl.clearColor(red: GLclampf, green:GLclampf, blue: GLclampf, alpha: GLclampf): void | 清空&lt;canvas&gt;指定的颜色。 |
| webgl.clear(mask:&nbsp;GLbitfield):&nbsp;void | 清空&lt;canvas&gt;。 | | webgl.clear(mask: GLbitfield): void | 清空&lt;canvas&gt;。 |
| webgl.drawArrays(mode:&nbsp;GLenum,&nbsp;first:;GLint,<br />&nbsp;count:&nbsp;GLsizei):&nbsp;void | 执行数据绘制。 | | webgl.drawArrays(mode: GLenum, first:;GLint, count: GLsizei): void | 执行数据绘制。 |
| webgl.flush():&nbsp;void | 刷新数据至GPU,清空缓冲区。 | | webgl.flush(): void | 刷新数据至GPU,清空缓冲区。 |
| webgl.createProgram():&nbsp;WebGLProgram&nbsp;\|&nbsp;null | 创建着色器程序对象。 | | webgl.createProgram(): WebGLProgram \| null | 创建着色器程序对象。 |
## 开发步骤 ## 开发步骤
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。 OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。
OpenHarmony支持三种系统类型: OpenHarmony支持三种系统类型:
1. 轻量系统(mini system),面向MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB 1. 轻量系统(mini system),面向MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB
2. 小型系统(small system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为1MiB 2. 小型系统(small system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为1MiB
3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB 3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB
...@@ -21,7 +21,7 @@ OpenHarmony支持三种系统类型: ...@@ -21,7 +21,7 @@ OpenHarmony支持三种系统类型:
#### 数据类型差异 #### 数据类型差异
大部分的32位系统采用的是ILP32,即int、long和pointer是32位长度。大部分的64位系统采用的是LP64,即long、long long、pointer是64位长度。Windows系统采用的是LLP64,即long long和pointer是64位长度。各系统基本数据长度对比如下表所示: 大部分的32位系统采用的是ILP32,即int、long和pointer是32位长度。大部分的64位系统采用的是LP64,即long、long long、pointer是64位长度。Windows系统采用的是LLP64,即long long和pointer是64位长度。各系统基本数据类型长度对比如下表所示:
| **TYPE** | **ILP32** | **LP64** | **LLP64** | **LP32** | **ILP64** | | **TYPE** | **ILP32** | **LP64** | **LLP64** | **LP32** | **ILP64** |
| --------- | --------- | -------- | --------- | -------- | --------- | | --------- | --------- | -------- | --------- | -------- | --------- |
...@@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型: ...@@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型:
| size_t | **4** | **8** | **8** | 4 | 8 | | size_t | **4** | **8** | **8** | 4 | 8 |
| pointer | **4** | **8** | **8** | 4 | 8 | | pointer | **4** | **8** | **8** | 4 | 8 |
上表中只包含了部分基本类型,下表分别将ILP32和LP64的sizeof和print`进行对比,展示了更全面的常量和类型对应的差异: 上表中只包含了部分基本类型,下表分别将ILP32和LP64的sizeof和print进行对比,展示了更全面的常量和类型对应的差异:
| Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | 备注 | | Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | 备注 |
| ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | | ------------------ | ------------ | ----------- | ----------- | ---------- | ------ |
...@@ -52,7 +52,7 @@ OpenHarmony支持三种系统类型: ...@@ -52,7 +52,7 @@ OpenHarmony支持三种系统类型:
| unsigned long int | 4 | %lu | **8** | %lu | 有差异 | | unsigned long int | 4 | %lu | **8** | %lu | 有差异 |
| long long | 8 | %lld | 8 | %lld | | | long long | 8 | %lld | 8 | %lld | |
| unsigned long long | 8 | %llu | 8 | %llu | | | unsigned long long | 8 | %llu | 8 | %llu | |
| type * | 4 | %p | **8** | %p | 有差异 | | type \* | 4 | %p | **8** | %p | 有差异 |
| pid_t | 4 | %d | 4 | %d | | | pid_t | 4 | %d | 4 | %d | |
| socklen_t | 4 | %u | 4 | %u | | | socklen_t | 4 | %u | 4 | %u | |
| off_t | 4 | %zd | **8** | %zd | 有差异 | | off_t | 4 | %zd | **8** | %zd | 有差异 |
...@@ -97,7 +97,7 @@ typedef struct tagFoo { ...@@ -97,7 +97,7 @@ typedef struct tagFoo {
#### 【规则】开发者贡献的代码应当遵循此规范,编写出可同时应用于32位和64位的代码 #### 【规则】开发者贡献的代码应当遵循此规范,编写出可同时应用于32位和64位的代码
【说明】由于OpenHarmony会长期同时存在32位的运行环境和64位的运行环境,为了代码的一致性,开发者在编码时需要充分考虑代码的可移植能力。 【说明】由于OpenHarmony会长期同时存在32位的运行环境和64位的运行环境,为了代码的一致性,开发者在编码时需要充分考虑代码的可移植能力。
### 数据类型定义和格式化 ### 数据类型定义和格式化
...@@ -121,11 +121,11 @@ typedef struct tagFoo { ...@@ -121,11 +121,11 @@ typedef struct tagFoo {
| double | 8 | 8 | %lf | 双精度浮点数 | | double | 8 | 8 | %lf | 双精度浮点数 |
| bool | 1 | 1 | %d | 布尔类型 | | bool | 1 | 1 | %d | 布尔类型 |
| uintptr_t | **4** | **8** | %zu | 会根据32位和64位的不同定义为不同的长度,用于可能存储指针的场景 | | uintptr_t | **4** | **8** | %zu | 会根据32位和64位的不同定义为不同的长度,用于可能存储指针的场景 |
| type * | **4** | **8** | %p | type *,可变长度类型,与uintptr_t等价,存在类型转换时建议使用uintptr_t | | type \* | **4** | **8** | %p | type \*,可变长度类型,与uintptr_t等价,存在类型转换时建议使用uintptr_t |
| nullptr_t | **4** | **8** | %p | 指针初始化 | | nullptr_t | **4** | **8** | %p | 指针初始化 |
| pid_t | 4 | 4 | %d | Linux内置,固定长度 | | pid_t | 4 | 4 | %d | Linux内置,固定长度 |
| socklen_t | 4 | 4 | %u | Linux内置,固定长度 | | socklen_t | 4 | 4 | %u | Linux内置,固定长度 |
| off_t/time_t | **4** | **8** | %zd | 可变长类型,有符号 | | off_t/time_t | **4** | **8** | %zd | 可变长类型,有符号 |
| size_t/pthread_t | **4** | **8** | %zu | 可变长度类型,无符号,仅用于调用库函数的兼容性要求(比如底层API中使用了size_t) | | size_t/pthread_t | **4** | **8** | %zu | 可变长度类型,无符号,仅用于调用库函数的兼容性要求(比如底层API中使用了size_t) |
上述类型定义在stddef.h(C)和cstdint(C++)标准库中,在采用#define重定义相关类型时,其源头应来自于上述类型。 上述类型定义在stddef.h(C)和cstdint(C++)标准库中,在采用#define重定义相关类型时,其源头应来自于上述类型。
...@@ -353,13 +353,13 @@ p = (int32_t *)malloc(sizeof(p) * ELEMENTS_NUMBER); ...@@ -353,13 +353,13 @@ p = (int32_t *)malloc(sizeof(p) * ELEMENTS_NUMBER);
【样例】 【样例】
```c ```c
#pragma pack(push) # 保存当前的对齐方式 #pragma pack(push) // 保存当前的对齐方式
#pragma pack(1) # 设置对齐方式为1字节对齐 #pragma pack(1) // 设置对齐方式为1字节对齐
struct test struct test
{ {
...... ......
}; };
#pragma pack(pop) # 恢复之前的对齐方式 #pragma pack(pop) // 恢复之前的对齐方式
``` ```
#### 【规则】涉及多机通信的消息结构体,需要对齐统一。基于兼容性考虑,可优先采用1字节对齐;禁止使用8字节对齐和64位数据类型以避免与32位系统通信错误 #### 【规则】涉及多机通信的消息结构体,需要对齐统一。基于兼容性考虑,可优先采用1字节对齐;禁止使用8字节对齐和64位数据类型以避免与32位系统通信错误
...@@ -494,7 +494,7 @@ printf("t2 = %lu\n", t2); ...@@ -494,7 +494,7 @@ printf("t2 = %lu\n", t2);
#### 【规则】当需要将指针作为基址,再按照字节计算偏移时,指针需要强制转换为uintptr_t或uint8_t *等单字节指针类型 #### 【规则】当需要将指针作为基址,再按照字节计算偏移时,指针需要强制转换为uintptr_t或uint8_t *等单字节指针类型
【说明】如果转换为整型,采用uint32_t强转,会出现指针被截断的情况,因此需要转换为uintptr_t。也可转换为单字节宽度的指针类型,如uint8_t *、char *等,转为上述方式后,偏移均被理解为字节。void *类型实际也会按照1字节进行偏移,但为了类型明确化,建议使用前面更明确的类型代替。 【说明】如果转换为整型,采用uint32_t强转,会出现指针被截断的情况,因此需要转换为uintptr_t。也可转换为单字节宽度的指针类型,如uint8_t \*、char \*等,转为上述方式后,偏移均被理解为字节。void \*类型实际也会按照1字节进行偏移,但为了类型明确化,建议使用前面更明确的类型代替。
【示例】 【示例】
...@@ -503,13 +503,13 @@ printf("t2 = %lu\n", t2); ...@@ -503,13 +503,13 @@ printf("t2 = %lu\n", t2);
void *pPkt = (void *)((uint32_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET); void *pPkt = (void *)((uint32_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET);
// 正确 // 正确
void *pPkt = (void *)((uintptr_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET);// C void *pPkt = (void *)((uintptr_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET); // C
void *pPkt = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(MSG_GET_DATA_ADDR(msgAddr)) + OFFSET); // C++ void *pPkt = reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(MSG_GET_DATA_ADDR(msgAddr)) + OFFSET); // C++
``` ```
#### 【规则】禁止指针与uint32_t之间相互赋值,包括函数参数传递 #### 【规则】禁止指针与uint32_t之间相互赋值,包括函数参数传递
【说明】如果要定义的变量可能是不确定长度的指针,使用void *;如果要定义的变量既可以是指针,也可以是整形,使用uintptr_t。 【说明】如果要定义的变量可能是不确定长度的指针,使用void \*;如果要定义的变量既可以是指针,也可以是整形,使用uintptr_t。
【示例】指针与整型的转换 【示例】指针与整型的转换
......
...@@ -75,6 +75,8 @@ ...@@ -75,6 +75,8 @@
### 绘图 ### 绘图
【规则】绘图中出现的英文单词大小写规则:术语、缩略语、专有名词(如开发板名称、设备名称)遵循[术语与缩略语](#%E6%9C%AF%E8%AF%AD%E5%8F%8A%E7%BC%A9%E7%95%A5%E8%AF%AD)的要求,全文统一大小写;其它英文单词遵循Sentence caps样式,即首个单词首字母大写。
【建议】字号:中英文正常字号均采用10.5pt(14px)。中文字号下限为9pt(12px),英文字号下限为8pt(11px)。 【建议】字号:中英文正常字号均采用10.5pt(14px)。中文字号下限为9pt(12px),英文字号下限为8pt(11px)。
【建议】优先使用灰色、蓝色两套配色,一张图建议不超过3套配色。 【建议】优先使用灰色、蓝色两套配色,一张图建议不超过3套配色。
......
...@@ -3292,7 +3292,7 @@ root { ...@@ -3292,7 +3292,7 @@ root {
busType = 0; // 0:i2c 1:spi busType = 0; // 0:i2c 1:spi
busNum = 5; busNum = 5;
busAddr = 0x15; busAddr = 0x15;
regWidth = 1; // 1btye regWidth = 1; // 1byte
} }
sensorIdAttr :: sensorIdInfo { sensorIdAttr :: sensorIdInfo {
chipName = "mxc6655xa"; chipName = "mxc6655xa";
......
...@@ -42,17 +42,17 @@ ...@@ -42,17 +42,17 @@
| 类名 | 方法名 | 描述 | | 类名 | 方法名 | 描述 |
| --- | ----- | ----| | --- | ----- | ----|
| Preferences | bool GetBool(const std::string &key, bool defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | int GetInt(const std::string &key, const int defValue = 0); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | std::string GetString(const std::string &key, const std::string &defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | std::string GetString(const std::string &key, const std::string &defValue = {}); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | bool GetBool(const std::string &key, bool defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | bool GetBool(const std::string &key, const bool defValue = false); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | float GetFloat(const std::string &key, float defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | float GetFloat(const std::string &key, const float defValue = 0); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | double GetDouble(const std::string &key, double defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | double GetDouble(const std::string &key, const double defValue = 0); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | int64_t GetLong(const std::string &key, int64_t defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | int64_t GetLong(const std::string &key, const int64_t defValue = 0); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
| Preferences | std::set\<std::string\> GetStringSet(const std::string &key, std::set\<std::string\> &defValue); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 | | Preferences | std::set\<std::string\> GetStringSet(const std::string &key, const std::set\<std::string\> &defValue = {}); | key:要获取的存储key名称,不能为空。<br/>defValue:若获取失败或value不存在返回此默认值。<br/>返回值:value。 |
**数据持久化** **数据持久化**
通过执行flush或者flushSync方法,应用可以将缓存的数据再次写回文本文件中进行持久化存储。 通过执行Flush()或者FlushSync()方法,应用可以将缓存的数据再次写回文本文件中进行持久化存储。
**表 5** 轻量级数据数据持久化接口 **表 5** 轻量级数据数据持久化接口
...@@ -122,14 +122,13 @@ ...@@ -122,14 +122,13 @@
5. 数据持久化。 5. 数据持久化。
应用存入数据到Preferences实例后,可以通过flush或者flushSync方法将Preferences实例回写到文件中。 应用存入数据到Preferences实例后,可以通过Flush()或者FlushSync()方法将Preferences实例回写到文件中。
```C++ ```C++
int err = pref->FlushSync(); int err = pref->FlushSync();
EXPECT_EQ(ret, E_OK); EXPECT_EQ(ret, E_OK);
``` ```
6. 订阅数据变化。 6. 订阅数据变化。
应用订阅数据变化需要指定PreferencesObserver作为回调方法。订阅的key的值发生变更后,当执行flush或者flushSync方法时,PreferencesObserver被触发回调。不再需要PreferencesObserver时请注销。 应用订阅数据变化需要指定PreferencesObserver作为回调方法。订阅的key的值发生变更后,当执行flush或者flushSync方法时,PreferencesObserver被触发回调。不再需要PreferencesObserver时请注销。
...@@ -192,4 +191,3 @@ ...@@ -192,4 +191,3 @@
EXPECT_EQ(ret, E_OK); EXPECT_EQ(ret, E_OK);
``` ```
...@@ -5,152 +5,160 @@ ...@@ -5,152 +5,160 @@
目前在系统的/system/bin目录下预置了hisysevent工具,开发者可以通过此工具实时订阅HiSysEvent事件及查询历史HiSysEvent事件。 目前在系统的/system/bin目录下预置了hisysevent工具,开发者可以通过此工具实时订阅HiSysEvent事件及查询历史HiSysEvent事件。
## 实时订阅HiSysEvent事件相关命令 ## 实时订阅HiSysEvent事件相关命令
- 实时订阅HiSysEvent事件的基础命令: - 实时订阅HiSysEvent事件的基础命令:
```
hisysevent -r
```
``` 选项说明:
hisysevent -r
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -r | 以缺省设置实时订阅HiSysEvent事件,在此种订阅方式下有任何实时HiSysEvent事件产生,都会在控制台上打印此HiSysEvent事件 | | -r | 以缺省设置实时订阅HiSysEvent事件,在此种订阅方式下有任何实时HiSysEvent事件产生,都会在控制台上打印此HiSysEvent事件 |
- 打开调试模式: - 打开调试模式:
```
hisysevent -r -d
```
``` 选项说明:
hisysevent -r -d
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -d | 在调试模式下实时订阅HiSysEvent事件 | | -d | 在调试模式下实时订阅HiSysEvent事件 |
- 通过事件标签方式实时订阅HiSysEvent事件: - 通过事件标签方式实时订阅HiSysEvent事件:
```
hisysevent -r -t <tag> [-c [WHOLE_WORD|PREFIX|REGULAR]]
```
``` 选项说明:
hisysevent -r -t <tag> [-c [WHOLE_WORD|PREFIX|REGULAR]]
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -t | 设置实时订阅的HiSysEvent事件标签,用来过滤订阅的HiSysEvent事件。 | | -t | 设置实时订阅的HiSysEvent事件标签,用来过滤订阅的HiSysEvent事件。 |
| -c | 设置实时订阅的HiSysEvent事件标签匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则。 | | -c | 设置实时订阅的HiSysEvent事件标签匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则。 |
命令实例: 命令实例:
```
``` # hisysevent -r -t "STA" -c PREFIX
# hisysevent -r -t "TAG" -c PREFIX {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963670809,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200750","HAPPEN_TIME":1501963670809,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"4973863135535405472","info_":""}
# hisysevent -r -t "TAw{0,1}" -c REGULAR {"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} # hisysevent -r -t "STAw{0,6}" -c REGULAR
# hisysevent -r -t "TAw+" -c REGULAR {"domain_":"WINDOWMANAGER","name_":"NO_FOCUS_WINDOW","type_":1,"time_":1501940269802,"tz_":"+0000","tag_":"TAG","pid_":1428,"tid_":1433,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"ARKUI","name_":"UI_BLOCK_6S","type_":1,"time_":1501940269812,"tz_":"+0000","tag_":"TAG1","pid_":1428,"tid_":1452,"uid_":10001,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963793206,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805200953","HAPPEN_TIME":1501963793206,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""}
``` # hisysevent -r -t "STA\w+" -c REGULAR
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963863393,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201103","HAPPEN_TIME":1501963863393,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"5522352691813553392","info_":""}
```
- 通过事件领域及事件名称的方式实时订阅HiSysEvent事件: - 通过事件领域及事件名称的方式实时订阅HiSysEvent事件:
```
hisysevent -r -o <domain> -n <eventName> [-c [WHOLE_WORD|PREFIX|REGULAR]]
```
``` 选项说明:
hisysevent -r -o <domain> -n <eventName> [-c [WHOLE_WORD|PREFIX|REGULAR]]
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -o | 设置实时订阅的HiSysEvent事件领域,用来过滤订阅的HiSysEvent事件。 | | -o | 设置实时订阅的HiSysEvent事件领域,用来过滤订阅的HiSysEvent事件。 |
| -n | 设置实时订阅的HiSysEvent事件名称,用来过滤订阅的HiSysEvent事件。 | | -n | 设置实时订阅的HiSysEvent事件名称,用来过滤订阅的HiSysEvent事件。 |
| -c | 设置实时订阅的HiSysEvent事件领域及事件名称的匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则。 | | -c | 设置实时订阅的HiSysEvent事件领域及事件名称的匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则。 |
命令实例: 命令实例:
```
# hisysevent -r -o "RELIABILITY" -n "APP_FREEZE"
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""}
# hisysevent -r -o "RELIABI\w{0,8}" -n "APP_FREEZE" -c REGULAR
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964144383,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501964144383,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""}
# hisysevent -r -o "RELIABI\w+" -c REGULAR
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964193466,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501964193466,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""}
```
``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
# hisysevent -r -o "DOMAINA" -n "EVENTNAMEA" > 当同时通过-t、-o及-n指定了相关订阅规则参数设置,则判断设置的事件标签是否为空,若不为空,则使用事件标签规则进行订阅,否则使用事件领域及事件名称订阅规则进行订阅。
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
# hisysevent -r -o "DOMAw{0,10}" -n "EVENTw+" -c REULAR
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""}
# hisysevent -r -o "DOMAw{0,10}" -c REGULAR
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":1501940269802,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"DOMAINABC","name_":"EVENTNAMEABC","type_":1,"time_":1501940269938,"tz_":"+0000","pid_":1428,"tid_":1336,"uid_":10002,"level_":"CRITICAL","info_":""}
{"domain_":"DOMAINABC","name_":"EVENTNAMEB","type_":1,"time_":1501940279938,"tz_":"+0000","pid_":1428,"tid_":1344,"uid_":10002,"level_":"CRITICAL","info_":""}
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 当同时通过-t、-o及-n指定了相关订阅规则参数设置,则判断设置的事件标签是否为空,若不为空,则使用事件标签规则进行订阅,否则使用事件领域及事件名称订阅规则进行订阅。
## 查询历史HiSysEvent事件相关命令 ## 查询历史HiSysEvent事件相关命令
- 查询历史HiSysEvent事件的基础命令: - 查询历史HiSysEvent事件的基础命令:
```
hisysevent -l
```
``` 选项说明:
hisysevent -l
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -l | 以缺省设置查询历史HiSysEvent事件,此次查询会返回最近不多于1000条的HiSysEvent事件。 | | -l | 以缺省设置查询历史HiSysEvent事件,此次查询会返回最近不多于1000条的HiSysEvent事件。 |
- 通过设置开始/结束时间,过滤查询历史HiSysEvent事件的结果的命令: - 通过设置开始/结束时间,过滤查询历史HiSysEvent事件的结果的命令:
```
hisysevent -l -s <begin time> -e <end time>
```
``` 选项说明:
hisysevent -l -s <begin time> -e <end time>
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -s | 设置查询历史HiSysEvent事件的开始时间,此次查询只会返回不早于该时间点的HiSysEvent事件。 | | -s | 设置查询历史HiSysEvent事件的开始时间,此次查询只会返回不早于该时间点的HiSysEvent事件。 |
| -e | 设置查询历史HiSysEvent事件的结束时间,此次查询只会返回不晚于该时间点的HiSysEvent事件。 | | -e | 设置查询历史HiSysEvent事件的结束时间,此次查询只会返回不晚于该时间点的HiSysEvent事件。 |
命令实例:
命令实例:
``` ```
# hisysevent -l -s 20207388633 -e 20207389000 # hisysevent -l -s 1501964222980 -e 1501964222996
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"GRAPHIC","name_":"NO_DRAW","type_":1,"time_":1501964222980,"tz_":"+0000","pid_":1505,"tid_":1585,"uid_":10002,"PID":1505,"UID":10002,"ABILITY_NAME":"","MSG":"It took 1957104259905ns to draw, UI took 0ns to draw, RSRenderThread took 8962625ns to draw, RSRenderThread dropped 0 UI Frames","level_":"MINOR","id_":"1708287249901948387","info_":"isResolved,eventId:0"}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222994,"tz_":"+0000","pid_":623,"tid_":1445,"uid_":1201,"SUB_EVENT_TYPE":"NO_DRAW","EVENT_TIME":"20170805201702","MODULE":"NO_DRAW","PNAME":"NO_DRAW","REASON":"NO_DRAW","DIAG_INFO":"","STACK":"SUMMARY:\n","HIVIEW_LOG_FILE_PATHS":["/data/log/faultlog/faultlogger/appfreeze-NO_DRAW-10002-20170805201702"],"DOMAIN":"GRAPHIC","STRING_ID":"NO_DRAW","PID":1505,"UID":10002,"PACKAGE_NAME":"NO_DRAW","PROCESS_NAME":"","MSG":"It took 1956945826265ns to draw, UI took 0ns to draw, RSRenderThread took 9863293ns to draw, RSRenderThread dropped 0 UI Frames\n","level_":"CRITICAL","tag_":"STABILITY","id_":"10448522101019619655","info_":""}
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} ```
```
- 通过设置最大数量值,限制查询历史HiSysEvent事件的数量: - 通过设置最大数量值,限制查询历史HiSysEvent事件的数量:
```
hisysevent -l -m <max hisysevent count>
```
``` 选项说明:
hisysevent -l -m <max hisysevent count>
```
选项说明:
| 选项名称 | 功能说明 | | 选项名称 | 功能说明 |
| -------- | -------- | | -------- | -------- |
| -m | 设置查询历史HiSysEvent事件的数量,有效值范围[0,1000],此次查询返回的HiSysEvent事件数目不会多于此值。 | | -m | 设置查询历史HiSysEvent事件的数量,有效值范围[0,1000],此次查询返回的HiSysEvent事件数目不会多于此值。 |
命令实例:
命令实例: ```
# hisysevent -l -s 1501964222980 -e 1501964222996 -m 1
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
```
## 系统事件合法性校验模式
``` - 打开系统事件合法性校验模式
# hisysevent -l -s 20207388633 -e 20207389000 -m 3
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} ```
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388900,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} hisysevent -v
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207389000,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} ```
# hisysevent -l -m 2
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388633,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""} 选项说明:
{"domain_":"DOMAINA","name_":"EVENTNAMEA","type_":1,"time_":20207388634,"tz_":"+0000","pid_":1428,"tid_":1333,"uid_":10002,"level_":"CRITICAL","info_":""}
``` | 选项名称 | 功能说明 |
| -------- | -------- |
| -v | 配合订阅命令-r及查询命令-l使用,当打开事件合法性校验模式,系统事件包含的非法内容会标记为红色高亮显示。 |
命令实例:
```
# hisysevent -v -l -s 1501964222980 -e 1501964222996
# 因为HAPPEN_TIME与VERSION没有在事件领域RELIABILITY所属的事件名称APP_FREEZE下进行yaml文件配置,属于非法内容,所以这两个键会被高亮显示为红色.
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""}
# hisysevent -v -r -o "RELIABILITY" -n "APP_FREEZE"
{"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964644584,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805202404","HAPPEN_TIME":1501964644584,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"11097868872446282676","info_":""}
```
\ No newline at end of file
...@@ -75,7 +75,7 @@ base/update # 升级子系统仓 ...@@ -75,7 +75,7 @@ base/update # 升级子系统仓
[update\_updateservice](https://gitee.com/openharmony/update_updateservice) [update\_updateservice](https://gitee.com/openharmony/update_updateservice)
[update\_updater](update\_updater) [update\_updater](https://gitee.com/openharmony/update_updater)
[update\_packaging\_tools](https://gitee.com/openharmony/update_packaging_tools) [update\_packaging\_tools](https://gitee.com/openharmony/update_packaging_tools)
# 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.
先完成此消息的编辑!
想要评论请 注册