提交 42ac460e 编写于 作者: L liyaoyao 提交者: Gitee

Signed-off-by: li-yaoyao777 <liyaoyao7@huawei.com>

Signed-off-by: Nliyaoyao <liyaoyao7@huawei.com>
...@@ -222,7 +222,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang ...@@ -222,7 +222,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-storage.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-system-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-system-storage.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-settings.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-settings.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-document.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-document.md @qinxiaowang
zh-cn/application-dev/reference/apis/js-apis-environment.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-environment.md @qinxiaowang
...@@ -258,7 +258,7 @@ zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen ...@@ -258,7 +258,7 @@ zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14
......
...@@ -7,16 +7,16 @@ ...@@ -7,16 +7,16 @@
- [OpenHarmony Release Notes](../release-notes/Readme.md) - [OpenHarmony Release Notes](../release-notes/Readme.md)
- Quick Start - Quick Start
- Getting Started - Getting Started
- [Preparations](quick-start/start-overview.md) - [Preparations](quick-start/start-overview.md)
- [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) - [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md)
- [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) - [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) - [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md) - [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md)
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md) - [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
...@@ -33,20 +33,19 @@ ...@@ -33,20 +33,19 @@
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md) - [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md)
- [Native APIs](napi/Readme-EN.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master) - [Codelabs](https://gitee.com/openharmony/codelabs)
- API References - API References
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs - Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms. The ability framework model has two forms:
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. - Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
| Item | FA Model | Stage Model | | Item | FA Model | Stage 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. | | 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.json5` 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). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
...@@ -27,8 +27,4 @@ In addition, the following differences exist in the development process: ...@@ -27,8 +27,4 @@ In addition, the following differences exist in the development process:
![lifecycle](figures/lifecycle.png) ![lifecycle](figures/lifecycle.png)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
...@@ -34,17 +34,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** ...@@ -34,17 +34,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
# Data Ability Development # Data Ability Development
## When to Use ## When to Use
A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices.
Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs.
## Available APIs ## Available APIs
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
...@@ -18,7 +21,7 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -18,7 +21,7 @@ Data ability providers can customize data access-related APIs such as data inser
|denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| |denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.| |insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.|
|openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.| |openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.|
|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\<Array\<string>>): void|Obtains the MIME type of a file.| |getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>): void|Obtains the MIME type of a file.|
|getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.| |getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.|
|executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.| |executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.|
|call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.| |call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
...@@ -115,7 +118,7 @@ Import the basic dependency packages and obtain the URI string for communicating ...@@ -115,7 +118,7 @@ Import the basic dependency packages and obtain the URI string for communicating
The basic dependency packages include: The basic dependency packages include:
- @ohos.ability.featureAbility - @ohos.ability.featureAbility
- @ohos.data.dataability - @ohos.data.dataAbility
- @ohos.data.rdb - @ohos.data.rdb
#### Data Ability API Development #### Data Ability API Development
...@@ -283,9 +286,3 @@ The basic dependency packages include: ...@@ -283,9 +286,3 @@ The basic dependency packages include:
] ]
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop Data abilities:
- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
...@@ -348,9 +348,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -348,9 +348,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
Now you've got a widget shown below. Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
The following samples are provided to help you better understand how to develop a widget on the FA model:
- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
...@@ -261,7 +261,3 @@ export default { ...@@ -261,7 +261,3 @@ export default {
}, },
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop a Page ability:
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -399,9 +399,3 @@ export default { ...@@ -399,9 +399,3 @@ export default {
} }
}; };
``` ```
## Samples
The following samples are provided to help you better understand how to develop a Service ability:
- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
# 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.json5` and `app.json5` 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.json5` 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.json5` file:
```json ```json
{ {
"module": { "module": {
...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h ...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h
The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 2** Ability APIs **Table 2** Ability APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
...@@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme
``` ```
import AbilityStage from "@ohos.application.AbilityStage" import AbilityStage from "@ohos.application.AbilityStage"
``` ```
2. Implement the `AbilityStage` class. 2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**.
```ts ```ts
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
...@@ -70,7 +71,7 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -70,7 +71,7 @@ To create Page abilities for an application in the stage model, you must impleme
```js ```js
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
4. Implement the lifecycle callbacks of the `Ability` class. 4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**.
In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md).
```ts ```ts
...@@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate") console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => { windowStage.loadContent("pages/index").then(() => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) console.log("MainAbility load content succeed")
}).catch((error) => { }).catch((error) => {
console.error("MainAbility load content failed with error: "+ JSON.stringify(error)) console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
}) })
...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme
} }
``` ```
### Obtaining AbilityStage and Ability Configurations ### Obtaining AbilityStage and Ability Configurations
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details.
The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:
```ts ```ts
import AbilityStage from "@ohos.application.AbilityStage" import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
...@@ -140,14 +144,14 @@ export default class MainAbility extends Ability { ...@@ -140,14 +144,14 @@ export default class MainAbility extends Ability {
console.log("MainAbility ability name" + abilityInfo.name) console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config let config = this.context.config
console.log("MyAbilityStage config language" + config.language) console.log("MainAbility config language" + config.language)
} }
} }
``` ```
### 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.json5`, 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.json5` file.
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -155,7 +159,7 @@ Declare the required permissions in the `module.json` file. ...@@ -155,7 +159,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 +170,11 @@ context.requestPermissionsFromUser(permissions).then((data) => { ...@@ -166,11 +170,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 +188,7 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -184,7 +188,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 +209,7 @@ export default class MainAbility extends Ability { ...@@ -205,7 +209,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|
...@@ -227,17 +231,16 @@ var want = { ...@@ -227,17 +231,16 @@ var want = {
"bundleName": "com.example.MyApplication", "bundleName": "com.example.MyApplication",
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
context.startAbility(want).then((data) => { context.startAbility(want).then(() => {
console.log("Succeed to start ability with data: " + JSON.stringify(data)) console.log("Succeed to start ability")
}).catch((error) => { }).catch((error) => {
console.error("Failed to start ability with error: "+ JSON.stringify(error)) console.error("Failed to start ability with error: "+ JSON.stringify(error))
}) })
``` ```
### 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 = {
...@@ -245,8 +248,8 @@ var want = { ...@@ -245,8 +248,8 @@ var want = {
"bundleName": "com.example.MyApplication", "bundleName": "com.example.MyApplication",
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
context.startAbility(want).then((data) => { context.startAbility(want).then(() => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) console.log("Succeed to start remote ability")
}).catch((error) => { }).catch((error) => {
console.error("Failed to start remote ability with error: " + JSON.stringify(error)) console.error("Failed to start remote ability with error: " + JSON.stringify(error))
}) })
...@@ -268,7 +271,7 @@ function getRemoteDeviceId() { ...@@ -268,7 +271,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:
...@@ -312,13 +315,9 @@ struct Index { ...@@ -312,13 +315,9 @@ struct Index {
console.info('Index onPageShow') console.info('Index onPageShow')
let newWant = globalThis.newWant let newWant = globalThis.newWant
if (newWant.hasOwnProperty("uri")) { if (newWant.hasOwnProperty("uri")) {
router.push({ uri: newWant.uri }); router.push({ url: newWant.uri });
globalThis.newWant = undefined globalThis.newWant = undefined
} }
} }
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop an ability on the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -247,7 +247,3 @@ try { ...@@ -247,7 +247,3 @@ try {
Logger.error(TAG, `caller release failed with ${error}`) Logger.error(TAG, `caller release failed with ${error}`)
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop an ability call in the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
Now you've got a widget shown below. Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
The following sample is provided to help you better understand how to develop a widget on the stage model:
- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility)
...@@ -26,7 +26,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -26,7 +26,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
1. Create a Service Extension ability. 1. Create a Service Extension ability.
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: 2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined (**entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts** by default) 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'
...@@ -61,9 +61,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -61,9 +61,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
2. Register the Service Extension ability. 2. Register the Service Extension ability.
Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. Declare the Service Extension ability in the **module.json5** file by setting its **type** attribute to **service**.
**module.json configuration example** **module.json5 configuration example**
```json ```json
"extensionAbilities":[{ "extensionAbilities":[{
...@@ -75,8 +75,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -75,8 +75,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts" "srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}] }]
``` ```
## Samples
The following sample is provided to help you better understand how to develop Service Extension abilities:
- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app ...@@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app
API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows: They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs - Native APIs
......
...@@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app ...@@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app
API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows: They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md)
- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md) - [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
- Native APIs - Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
......
...@@ -71,7 +71,3 @@ httpRequest.request( ...@@ -71,7 +71,3 @@ httpRequest.request(
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Samples
The following sample is provided to help you better understand how to develop the socket connection feature:
- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
...@@ -6,6 +6,7 @@ The distributed data objects allow data across devices to be processed like loca ...@@ -6,6 +6,7 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs ## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance ### Creating a Distributed Data Object Instance
...@@ -93,7 +94,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -93,7 +94,7 @@ The following example shows how to implement a distributed data object synchroni
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
``` ```
4. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes. 4. Observe the data changes of the distributed data object. You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes.
The sample code is as follows: The sample code is as follows:
...@@ -107,7 +108,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -107,7 +108,7 @@ The following example shows how to implement a distributed data object synchroni
}); });
} }
} }
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback. // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this)); local_object.on("change", this.changeCallback.bind(this));
``` ```
...@@ -138,13 +139,13 @@ The following example shows how to implement a distributed data object synchroni ...@@ -138,13 +139,13 @@ The following example shows how to implement a distributed data object synchroni
```js ```js
console.info("name " + local_object["name"]); console.info("name " + local_object["name"]);
``` ```
7. Unsubscribe from data changes. You can specify the callback to unsubscribe from. If you do not specify the callback, all data change callbacks of the distributed data object will be unsubscribed from. 7. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
The sample code is as follows: The sample code is as follows:
```js ```js
// Unsubscribe from the specified data change callback. // Unregister the specified data change callback.
local_object.off("change", changeCallback); local_object.off("change", changeCallback);
// Unsubscribe from all data change callbacks. // Unregister all data change callbacks.
local_object.off("change"); local_object.off("change");
``` ```
8. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 8. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
...@@ -156,13 +157,13 @@ The following example shows how to implement a distributed data object synchroni ...@@ -156,13 +157,13 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("status", this.statusCallback); local_object.on("status", this.statusCallback);
``` ```
9. Unsubscribe from the status changes of the distributed data object. You can specify the callback to unsubscribe from. If you do not specify the callback, this API unsubscribes from all callbacks of this distributed data object. 9. Unsubscribe from the status changes of the distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
The sample code is as follows: The sample code is as follows:
```js ```js
// Unsubscribe from the specified status change callback. // Unregister the specified status change callback.
local_object.off("status", statusCallback); local_object.off("status", statusCallback);
// Unsubscribe from all status change callbacks. // Unregister all status change callbacks.
local_object.off("status"); local_object.off("status");
``` ```
10. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. 10. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
...@@ -171,4 +172,12 @@ The following example shows how to implement a distributed data object synchroni ...@@ -171,4 +172,12 @@ The following example shows how to implement a distributed data object synchroni
```js ```js
local_object.setSessionId(""); local_object.setSessionId("");
``` ```
## Development Example
The following example is provided for you to better understand the development of distributed data objects:
- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad)
When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network.
...@@ -6,20 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,20 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| Category | API | Description | | API | Description |
| -------------------------- | ------------------------------------------------------------ | ----------------------------------------------- | | ------------------------------------------------------------ | ----------------------------------------------- |
| Creating a distributed database | createKVManager(config:&nbsp;KVManagerConfig,&nbsp;callback:&nbsp;AsyncCallback&lt;KVManager&gt;):&nbsp;void<br>createKVManager(config:&nbsp;KVManagerConfig):&nbsp;Promise&lt;KVManager> | Creates a **KVManager** object for database management.| | createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T&nbsp;extends&nbsp;KVStore&gt;(storeId:&nbsp;string,&nbsp;options:&nbsp;Options,&nbsp;callback:&nbsp;AsyncCallback&lt;T&gt;):&nbsp;void<br>getKVStore&lt;T&nbsp;extends&nbsp;KVStore&gt;(storeId:&nbsp;string,&nbsp;options:&nbsp;Options):&nbsp;Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.| | getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options,callback:AsyncCallback&lt;T&gt;):void<br>getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options):Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store| put(key:&nbsp;string,&nbsp;value:&nbsp;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void<br>put(key:&nbsp;string,&nbsp;value:&nbsp;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;boolean):&nbsp;Promise&lt;void> | Inserts and updates data. | | put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback&lt;void&gt;):void<br>put(key:string,value:Uint8Array\|string\|number\|boolean):Promise&lt;void> | Inserts and updates data. |
| Managing data in a distributed KV store| delete(key:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void<br>delete(key:&nbsp;string):&nbsp;Promise&lt;void> | Deletes data. | | delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br>delete(key:string):Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store| get(key:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;boolean&nbsp;\|&nbsp;number&gt;):&nbsp;void<br>get(key:&nbsp;string):&nbsp;Promise&lt;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;boolean&nbsp;\|&nbsp;number> | Queries data. | | get(key:string,callback:AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;):void<br>get(key:string):Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| Subscribing to changes in the distributed data | on(event:&nbsp;'dataChange',&nbsp;type:&nbsp;SubscribeType,&nbsp;observer:&nbsp;Callback&lt;ChangeNotification&gt;):&nbsp;void<br>on(event:&nbsp;'syncComplete',&nbsp;syncCallback:&nbsp;Callback&lt;Array&lt;[string,&nbsp;number]&gt;&gt;):&nbsp;void | Subscribes to data changes in the KV store. | | on(event:'dataChange',type:SubscribeType,observer:Callback&lt;ChangeNotification&gt;):void<br>on(event:'syncComplete',syncCallback:Callback&lt;Array&lt;[string,number]&gt;&gt;):void | Subscribes to data changes in the KV store. |
| Synchronizing data across devices | sync(deviceIdList:&nbsp;string[],&nbsp;mode:&nbsp;SyncMode,&nbsp;allowedDelayMs?:&nbsp;number):&nbsp;void | Triggers database synchronization in manual mode. | | sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. |
...@@ -34,11 +34,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -34,11 +34,14 @@ The following uses a single KV store as an example to describe the development p
``` ```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance. (1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js
```
let kvManager; let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
...@@ -60,10 +63,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -60,10 +63,13 @@ The following uses a single KV store as an example to describe the development p
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
} }
``` ```
3. Create and obtain a single KV store. 3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. (1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -90,10 +96,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -90,10 +96,11 @@ The following uses a single KV store as an example to describe the development p
} }
``` ```
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. >
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/> 4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
...@@ -102,8 +109,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -102,8 +109,10 @@ The following uses a single KV store as an example to describe the development p
``` ```
5. Write data to the single KV store. 5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store. (1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store: The following is the sample code for writing key-value pairs of the string type into the single KV store:
...@@ -124,8 +133,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -124,8 +133,10 @@ The following uses a single KV store as an example to describe the development p
``` ```
6. Query data in the single KV store. 6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store.
2. Query data from the single KV store. (1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store: The following is the sample code for querying data of the string type from the single KV store:
```js ```js
...@@ -150,7 +161,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -150,7 +161,11 @@ The following uses a single KV store as an example to describe the development p
7. Synchronize data to other devices.<br/> 7. Synchronize data to other devices.<br/>
Select the devices in the same network and the synchronization mode to synchronize data. Select the devices in the same network and the synchronization mode to synchronize data.
The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms. > **NOTE**
>
> The APIs of the `deviceManager` module are system interfaces.
The following is the sample code for synchronizing data in a single KV store:
```js ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
...@@ -159,7 +174,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -159,7 +174,7 @@ The following uses a single KV store as an example to describe the development p
deviceManager.createDeviceManager("bundleName", (err, value) => { deviceManager.createDeviceManager("bundleName", (err, value) => {
if (!err) { if (!err) {
devManager = value; devManager = value;
// Obtain deviceIds. // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync().
let deviceIds = []; let deviceIds = [];
if (devManager != null) { if (devManager != null) {
var devices = devManager.getTrustedDeviceListSync(); var devices = devManager.getTrustedDeviceListSync();
...@@ -168,6 +183,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -168,6 +183,7 @@ The following uses a single KV store as an example to describe the development p
} }
} }
try{ try{
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
}catch (e) { }catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
......
# Distributed Data Service Overview<a name="EN-US_TOPIC_0000001183067628"></a> # Distributed Data Service Overview
The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. The distributed data service (DDS) implements distributed database collaboration across devices for applications.
## Basic Concepts<a name="section17506141102520"></a> Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts
- **KV data model** - **KV data model**
...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati ...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles<a name="section315111581616"></a> ## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following:
...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d
![](figures/en-us_image_0000001183386164.png) ![](figures/en-us_image_0000001183386164.png)
## Constraints<a name="section95382010203311"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
- The KV data model specifications supported by the DDS are as follows: - The KV data model specifications supported by the DDS are as follows:
......
# RDB Overview<a name="EN-US_TOPIC_0000001231030607"></a> # RDB Overview
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. 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.
## Basic Concepts<a name="section1063573420813"></a> You do not need to care about the implementation of the database locking mechanism.
- **RDB** ## Basic concepts
A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store. - **RDB**
- **Predicate** A type of database created on the basis of relational models. The RDB stores data in rows and columns. A RDB is also called RDB store.
A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. - **Predicate**
- **Result set** A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions.
A set of query results used to access the data. You can access the required data in a result set in flexible modes. - **Result set**
- **SQLite database** A set of query results used to access data. You can access the required data in a result set in flexible modes.
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability \(ACID\). - **SQLite database**
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability (ACID).
## Working Principles<a name="section4810552814"></a> ## Working Principles
The RDB provides a common operation interface for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. The RDB provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features.
**Figure 1** How RDB works<a name="fig1826214361535"></a> **Figure 1** How RDB works
![](figures/how-rdb-works.png "how-rdb-works")
## Default Settings<a name="section176091243121218"></a> ![how-rdb-works](figures/how-rdb-works.png)
- The default database logging mode is write-ahead logging \(WAL\). ## Default Settings
- The default database flush mode is Full mode.
- The default shared memory used by the OpenHarmony database is 2 MB.
## Constraints<a name="section929813398308"></a> - The default RDB logging mode is Write Ahead Log (WAL).
- The default data flushing mode is **FULL** mode.
- The default size of the shared memory used by an OpenHarmony database is 2 MB.
- A maximum of four connection pools can be connected to an RDB to manage read and write operations. ## Constraints
- To ensure data accuracy, the RDB supports only one write operation at a time. - A maximum of four connection pools can be connected to an RDB to manage read and write operations.
- To ensure data accuracy, the RDB supports only one write operation at a time.
...@@ -76,19 +76,24 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -76,19 +76,24 @@ Use the following APIs to delete a **Storage** instance or data file.
1. Import **@ohos.data.storage** and related modules to the development environment. 1. Import **@ohos.data.storage** and related modules to the development environment.
```js ```js
import dataStorage from '@ohos.data.storage' import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility' // Used to obtain the file storage path. import featureAbility from '@ohos.ability.featureAbility'; // Used to obtain the file storage path.
``` ```
2. Create a **Storage** instance. 2. Create a **Storage** instance.
Read the specified file and load its data to the **Storage** instance for data operations. Read the specified file and load its data to the **Storage** instance for data operations.
```js ```js
var context = featureAbility.getContext() var path;
var path = await context.getFilesDir() var context = featureAbility.getContext();
let promise = dataStorage.getStorage(path + '/mystore') context.getFilesDir().then((filePath) => {
``` path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promise = dataStorage.getStorage(path + '/mystore');
```
3. Write data. 3. Write data.
...@@ -97,14 +102,14 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -97,14 +102,14 @@ Use the following APIs to delete a **Storage** instance or data file.
```js ```js
promise.then((storage) => { promise.then((storage) => {
let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance. let getPromise = storage.put('startup', 'auto'); // Save data to the Storage instance.
getPromise.then(() => { getPromise.then(() => {
console.info("Put the value of startup successfully.") console.info("Succeeded in putting the value of startup.");
}).catch((err) => { }).catch((err) => {
console.info("Put the value of startup failed with err: " + err) console.info("Failed to put the value of startup with err: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Get the storage failed") console.info("Failed to get the storage.");
}) })
``` ```
...@@ -115,14 +120,14 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -115,14 +120,14 @@ Use the following APIs to delete a **Storage** instance or data file.
```js ```js
promise.then((storage) => { promise.then((storage) => {
let getPromise = storage.get('startup', 'default') let getPromise = storage.get('startup', 'default');
getPromise.then((value) => { getPromise.then((value) => {
console.info("The value of startup is " + value) console.info("The value of startup is " + value);
}).catch((err) => { }).catch((err) => {
console.info("Get the value of startup failed with err: " + err) console.info("Failed to get the value of startup with err: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Get the storage failed") console.info("Failed to get the storage.");
}) })
``` ```
...@@ -142,15 +147,15 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -142,15 +147,15 @@ Use the following APIs to delete a **Storage** instance or data file.
```js ```js
promise.then((storage) => { promise.then((storage) => {
var observer = function (key) { var observer = function (key) {
console.info("The key of " + key + " changed.") console.info("The key of " + key + " changed.");
} }
storage.on('change', observer) storage.on('change', observer);
storage.putSync('startup', 'auto') // Modify data in the Storage instance. storage.putSync('startup', 'auto'); // Modify data in the Storage instance.
storage.flushSync() // Trigger the StorageObserver callback. storage.flushSync(); // Trigger the StorageObserver callback.
storage.off(...change..., observer) // Unsubscribe from the data changes. storage.off('change', observer); // Unsubscribe from the data changes.
}).catch((err) => { }).catch((err) => {
console.info("Get the storage failed") console.info("Failed to get the storage.");
}) })
``` ```
...@@ -160,11 +165,11 @@ Use the following APIs to delete a **Storage** instance or data file. ...@@ -160,11 +165,11 @@ Use the following APIs to delete a **Storage** instance or data file.
Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
```js ```js
let promise = dataStorage.deleteStorage(path + '/mystore') let promise = dataStorage.deleteStorage(path + '/mystore');
promise.then(() => { promise.then(() => {
console.info("Deleted successfully.") console.info("Succeeded in deleting the storage.");
}).catch((err) => { }).catch((err) => {
console.info("Deleted failed with err: " + err) console.info("Failed to deleted the storage with err: " + err);
}) })
``` ```
# Lightweight Data Store Overview<a name="EN-US_TOPIC_0000001230752103"></a> # Lightweight Data Store Overview
Lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight **Storage** instance, data in the **Storage** instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. The lightweight data store is applicable to access and persistence of data in the key-value structure.
## Basic Concepts<a name="section1055404171115"></a> After an application obtains a lightweight store instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
- **Key-Value data structure** You do not need to care about the implementation of the database lock mechanism.
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. ## Basic Concepts
- **Non-relational database** - **Key-value structure**
A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. The data in a non-relational database is independent. A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
- **Non-relational database**
## Working Principles<a name="section682631371115"></a> A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent.
1. When an application loads data from a specified **Storage** file to a **Storage** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file. ## Working Principles
2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method.
**Figure 1** How lightweight data store works<a name="fig1657785713509"></a> 1. An application can load data from a specified **Storage** file to a **Storage** instance. The system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file.
2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method.
**Figure 1** Working mechanism
![](figures/en-us_image_0000001199139454.png) ![](figures/en-us_image_0000001199139454.png)
## Constraints<a name="section17243172883219"></a> ## Constraints
- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters.
- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters.
- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The value of the string type can be empty, but cannot exceed 8192 bytes if not empty.
## Device Usage Statistics Development # Device Usage Statistics Development
## When to Use ## When to Use
...@@ -56,7 +56,9 @@ import stats from '@ohos.bundleState'; ...@@ -56,7 +56,9 @@ import stats from '@ohos.bundleState';
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.queryBundleActiveStates(0, 20000000000000, (err, res) => { stats.queryBundleActiveStates(0, 20000000000000, (err, res) => {
if(err.code == 0) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE queryBundleActiveStates callback success.'); console.log('BUNDLE_ACTIVE queryBundleActiveStates callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates callback number : ' + (i + 1));
...@@ -74,21 +76,23 @@ import stats from '@ohos.bundleState'; ...@@ -74,21 +76,23 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Use a promise to return the result. // Use a promise to return the result.
stats.queryBundleStateInfos(0, 20000000000000).then( res => { stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1; let i = 1;
for(let key in res){ for (let key in res) {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
}); });
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.queryBundleStateInfos(0, 20000000000000, (err, res) => { stats.queryBundleStateInfos(0, 20000000000000, (err, res) => {
if(err.code == 0) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos callback success.');
let i = 1; let i = 1;
for(let key in res){ for(let key in res){
...@@ -108,26 +112,26 @@ import stats from '@ohos.bundleState'; ...@@ -108,26 +112,26 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Use a promise to return the result. // Use a promise to return the result.
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
}); });
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.queryCurrentBundleActiveStates(0, 20000000000000, (err, res) => { stats.queryCurrentBundleActiveStates(0, 20000000000000, (err, res) => {
if(err.code == 0) { if (err) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback result ' + JSON.stringify(res[i]));
} }
} else {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code);
} }
}); });
``` ```
...@@ -138,26 +142,26 @@ import stats from '@ohos.bundleState'; ...@@ -138,26 +142,26 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Use a promise to return the result. // Use a promise to return the result.
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
}); });
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => {
if(err.code == 0) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback result ' + JSON.stringify(res[i]));
} }
} else {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code);
} }
}); });
``` ```
...@@ -168,18 +172,18 @@ import stats from '@ohos.bundleState'; ...@@ -168,18 +172,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Use a promise to return the result. // Use a promise to return the result.
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if(err.code === 0) { if (err) {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
} else {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
``` ```
...@@ -190,18 +194,18 @@ import stats from '@ohos.bundleState'; ...@@ -190,18 +194,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Use a promise to return the result. // Use a promise to return the result.
stats.isIdleState("com.ohos.camera").then( res => { stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
}); });
// Use an asynchronous callback to return the result. // Use an asynchronous callback to return the result.
stats.isIdleState("com.ohos.camera", (err, res) => { stats.isIdleState("com.ohos.camera", (err, res) => {
if(err.code === 0) { if (err) {
console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res));
} else {
console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res));
} }
}); });
``` ```
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
## When to Use ## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc. The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs ## Available APIs
...@@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord ...@@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord
| API | Description | | API | Description |
| -------- | -------- | | -------- | -------- |
| isGeoServiceAvailable(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Checks&nbsp;whether&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;is&nbsp;available.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. |
| isGeoServiceAvailable()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Checks&nbsp;whether&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;is&nbsp;available.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | isGeoServiceAvailable() : Promise&lt;boolean&gt; | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | Converts&nbsp;coordinates&nbsp;into&nbsp;geographic&nbsp;description&nbsp;through&nbsp;reverse&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt;; | Converts&nbsp;coordinates&nbsp;into&nbsp;geographic&nbsp;description&nbsp;through&nbsp;reverse&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | Converts&nbsp;geographic&nbsp;description&nbsp;into&nbsp;coordinates&nbsp;through&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts&nbsp;geographic&nbsp;description&nbsp;into&nbsp;coordinates&nbsp;through&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. | | getAddressesFromLocationName(request: GeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. |
## How to Develop ## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. > 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. 1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
...@@ -45,7 +46,7 @@ The following table describes APIs available for mutual conversion between coord ...@@ -45,7 +46,7 @@ The following table describes APIs available for mutual conversion between coord
}); });
``` ```
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_. Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
- Call **getAddressesFromLocationName** to convert geographic description into coordinates. - Call **getAddressesFromLocationName** to convert geographic description into coordinates.
``` ```
...@@ -55,6 +56,6 @@ The following table describes APIs available for mutual conversion between coord ...@@ -55,6 +56,6 @@ The following table describes APIs available for mutual conversion between coord
}); });
``` ```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the _API Reference_. Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
"reqPermissions":[ "reqPermissions":[
{ {
"name":"ohos.permission.ACCELEROMETER", "name":"ohos.permission.ACCELEROMETER",
"reason"":"", "reason":"",
"usedScene":{ "usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"], "ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse" "when":"inuse"
...@@ -45,7 +45,7 @@ ...@@ -45,7 +45,7 @@
}, },
{ {
"name":"ohos.permission.GYROSCOPE", "name":"ohos.permission.GYROSCOPE",
"reason"":"", "reason":"",
"usedScene":{ "usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"], "ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse" "when":"inuse"
...@@ -53,7 +53,7 @@ ...@@ -53,7 +53,7 @@
}, },
{ {
"name":"ohos.permission.ACTIVITY_MOTION", "name":"ohos.permission.ACTIVITY_MOTION",
"reason"":"ACTIVITY_MOTION_TEST", "reason":"ACTIVITY_MOTION_TEST",
"usedScene":{ "usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"], "ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse" "when":"inuse"
...@@ -61,7 +61,7 @@ ...@@ -61,7 +61,7 @@
}, },
{ {
"name":"ohos.permission.READ_HEALTH_DATA", "name":"ohos.permission.READ_HEALTH_DATA",
"reason"":"HEALTH_DATA_TEST", "reason":"HEALTH_DATA_TEST",
"usedScene":{ "usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"], "ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse" "when":"inuse"
...@@ -123,8 +123,3 @@ ...@@ -123,8 +123,3 @@
console.error(error); console.error(error);
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop sensors:
- [`Sensor`: sensor (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)
# Sensor Overview # Sensor Overview
Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications.
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows:
...@@ -37,7 +37,7 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -37,7 +37,7 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
**Figure 1** How the sensor works **Figure 1** How the sensor works
![en-us_image_0000001226521897.png](figures/en-us_image_0000001226521897.png) ![fad1a124-a90e-460f-84fc-e87d6caebb21](figures/fad1a124-a90e-460f-84fc-e87d6caebb21.png)
- Sensor API: provides APIs for performing basic operations on sensors, including querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. This module makes application development simpler. - Sensor API: provides APIs for performing basic operations on sensors, including querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. This module makes application development simpler.
......
...@@ -16,7 +16,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -16,7 +16,7 @@ The following table lists the USB APIs currently available. For details, see the
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | | hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. | | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. | | connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
...@@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The ...@@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The
Claim the corresponding interface from deviceList. Claim the corresponding interface from deviceList.
interface1 must be one present in the device configuration. interface1 must be one present in the device configuration.
*/ */
usb.claimInterface(pipe , interface1, true); usb.claimInterface(pipe, interface1, true);
``` ```
4. Perform data transfer. 4. Perform data transfer.
......
...@@ -5,53 +5,55 @@ ...@@ -5,53 +5,55 @@
You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls. You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls.
For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md).
## Available APIs ## Available APIs
| Module| API| Description| | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.| | ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result.| | ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result.|
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result.| | ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified effect. This API uses a callback to return the result.| | ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode):&nbsp;Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result.| | ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result.|
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Stops vibration. This API uses a callback to return the result.| | ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result.|
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the **config.json** file. 1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file.
``` ```
"reqPermissions":[ "reqPermissions": [
{ {
"name":"ohos.permission.ACCELEROMETER", "name": "ohos.permission.ACCELEROMETER",
"reason"":"", "reason": "",
"usedScene":{ "usedScene": {
"ability""[ "ability": [
".MainAbility" ".MainAbility"
], ],
"when":"inuse" "when": "inuse"
} }
}, },
{ {
"name":"ohos.permission.VIBRATE", "name": "ohos.permission.VIBRATE",
"reason"":"", "reason": "",
"usedScene":{ "usedScene": {
"ability""[ "ability": [
".MainAbility" ".MainAbility"
], ],
"when":"inuse" "when": "inuse"
} }
}, },
{ {
"name":"ohos.permission.ACTIVITY_MOTION", "name": "ohos.permission.ACTIVITY_MOTION",
"reason"":"", "reason": "",
"usedScene":{ "usedScene": {
"ability""[ "ability": [
".MainAbility" ".MainAbility"
], ],
"when":"inuse" "when": "inuse"
} }
}, },
] ]
...@@ -63,9 +65,9 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -63,9 +65,9 @@ You can set different vibration effects as needed, for example, customizing the
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{ vibrator.vibrate(1000).then((error)=>{
if (error){ // The call fails, and error.code and error.message are printed. if (error){ // The call fails, and error.code and error.message are printed.
console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{ // The call is successful, and the device starts to vibrate. }else{ // The call is successful, and the device starts to vibrate.
console.log("Promise returned to indicate a successful vibration.") Console.log("Promise returned to indicate a successful vibration.")
}; };
}) })
``` ```
...@@ -76,15 +78,9 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -76,15 +78,9 @@ You can set different vibration effects as needed, for example, customizing the
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
if(error){ // The call fails, and error.code and error.message are printed. if(error){ // The call fails, and error.code and error.message are printed.
console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{ // The call is successful, and the device stops vibrating. }else{ // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop."); Console.log("Promise returned to indicate a successful stop.");
}; };
}) })
``` ```
## Samples
The following sample is provided to help you better understand how to develop vibrators:
- [`Vibrator`: vibrator (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator)
...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## Constraints ## Constraints
When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**.
...@@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex ...@@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex
``` ```
2. Tap the run button on the application UI to run the project. 2. Tap the run button on the application UI to run the project.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest`: Event Logging Test (JavaScript) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest)
...@@ -39,38 +39,38 @@ function printfDescription(obj) { ...@@ -39,38 +39,38 @@ function printfDescription(obj) {
// Set the player callbacks. // Set the player callbacks.
function setCallBack(audioPlayer) { function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the 'stop' event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success'); console.info('audio stop success');
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]); printfDescription(arrlist[i]);
...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { ...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) {
} else { } else {
console.log(`audio getTrackDescription fail, error:${error.message}`); console.log(`audio getTrackDescription fail, error:${error.message}`);
} }
audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
}); });
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
}); });
audioPlayer.on('error', (error) => { // Set the 'error' event callback. audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
...@@ -92,10 +92,10 @@ function setCallBack(audioPlayer) { ...@@ -92,10 +92,10 @@ function setCallBack(audioPlayer) {
} }
async function audioPlayerDemo() { async function audioPlayerDemo() {
// 1. Create an audioPlayer instance. // 1. Create an AudioPlayer instance.
let audioPlayer = media.createAudioPlayer(); let audioPlayer = media.createAudioPlayer();
setCallBack(audioPlayer); // Set the event callbacks. setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file selected by the user. // 2. Set the URI of the audio file.
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
...@@ -119,23 +119,23 @@ import fileIO from '@ohos.fileio' ...@@ -119,23 +119,23 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
async audioPlayerDemo() { async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
...@@ -161,20 +161,20 @@ export class AudioDemo { ...@@ -161,20 +161,20 @@ export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
private isNextMusic = false; private isNextMusic = false;
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play success'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented.
} else { } else {
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
} }
}); });
...@@ -197,8 +197,8 @@ export class AudioDemo { ...@@ -197,8 +197,8 @@ export class AudioDemo {
} }
async audioPlayerDemo() { async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
...@@ -223,19 +223,19 @@ import fileIO from '@ohos.fileio' ...@@ -223,19 +223,19 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute. audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Sets the 'play' event callback to start loop playback. audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
console.info('audio play success'); console.info('audio play success');
}); });
} }
async audioPlayerDemo() { async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
...@@ -251,12 +251,3 @@ export class AudioDemo { ...@@ -251,12 +251,3 @@ export class AudioDemo {
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio playback:
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -185,11 +185,3 @@ export class AudioRecorderDemo { ...@@ -185,11 +185,3 @@ export class AudioRecorderDemo {
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio recording:
- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -445,8 +445,3 @@ export class VideoPlayerDemo { ...@@ -445,8 +445,3 @@ export class VideoPlayerDemo {
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop video playback:
- [`VideoPlayer`: Video Playback (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer)
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native_window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of ...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of
double position[2] = {10.0, 15.0}; double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
``` ```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
...@@ -169,9 +169,3 @@ if (this.subscriber != null) { ...@@ -169,9 +169,3 @@ if (this.subscriber != null) {
}) })
} }
``` ```
## Samples
The following sample is provided to help you better understand how to use the common event functionality:
- [`CommonEvent`: eTS Common Event (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent)
...@@ -256,10 +256,3 @@ function cancelCallback(err) { ...@@ -256,10 +256,3 @@ function cancelCallback(err) {
Notification.cancel(1, "label", cancelCallback) Notification.cancel(1, "label", cancelCallback)
``` ```
## Samples
The following sample is provided to help you better understand how to develop notification functions:
[`Notification`: Notification (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification)
\ No newline at end of file
...@@ -6,10 +6,7 @@ ...@@ -6,10 +6,7 @@
- [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md) - [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md) - [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md) - [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md)
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md) - [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [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)
- [SysCap](syscap.md) - [SysCap](syscap.md)
# Guide to Switching to Full SDK
Both the public SDK and full SDK are toolkits for application development.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
## Downloading the Full SDK (of 3.1.1 Release in this example)
Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md).
![image-20220613161049897](figures/en-us_image_0000001655128646.png)
## Checking the Local SDK Location<br>In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
![](figures/en-us_image_0000001655128939.png)
![image-20220613160524053](figures/en-us_image_0000001655128998.png)
## Replacing the SDK
1. Make sure the downloaded SDK is a full SDK.
a. Verify that the name of the downloaded file contains **sdk-full**.
![image-20220613220702504](figures/en-us_image_0000001655129232.png)
b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**).
Note: The criteria for identifying system APIs are subject to the released API documentation.
2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example.
a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip`
![image-20220613165018184](figures/en-us_image_0000001655129264.png)
b. Replace the SDK files.
Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
Go to the obtained location of the local installed SDK and back up the files therein.
![image-20220613161352157](figures/en-us_image_0000001655129041.png)
Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**.
![image-20220613165018184](figures/en-us_image_0000001655129398.png)
The configuration in the **oh-uni-package.json** file is as follows:
```
{
"apiVersion": "8",
"displayName": "Ets",
"meta": {
"metaVersion": "3.0.0"
},
"path": "ets",
"releaseType": "Release",
"version": "3.1.6.6"
}
```
**Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten.
Copy the full SDK to the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK.
Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package.
![image-20220613171111405](figures/en-us_image_0000001655129333.png)
c. Check for system APIs.
![image-20220613213038104](figures/en-us_image_0000001655129372.png)
...@@ -99,50 +99,6 @@ Example of the **module.json** file: ...@@ -99,50 +99,6 @@ Example of the **module.json** file:
"resource": "$profile:config_file2" "resource": "$profile:config_file2"
} }
], ],
"metadata": [
{
"name": "string",
"value": "string",
"resource": "$profile:config_file1"
},
{
"name": "string",
"value": "string",
"resource": "$profile:config_file2"
}
],
"abilities": [
{
"name": "MainAbility",
"srcEntrance" : "./login/MyMainAbility.ts",
"description": "$string:description_main_ability",
"icon": "$media:icon",
"label": "HiMusic",
"visible": true,
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
],
"uris": [ ]
}
],
"backgroundModes": [
"dataTransfer",
"audioPlayback",
"audioRecording",
"location",
"bluetoothInteraction",
"multiDeviceConnection",
"wifiInteraction",
"voip",
"taskKeeping"
],
}
],
"abilities": [ "abilities": [
{ {
"name": "MainAbility", "name": "MainAbility",
......
# Getting Started with eTS in the Low-Code Approach # Getting Started with eTS in the Low-Code Approach
> **NOTE**<br/>This feature is supported in DevEco Studio V3.0 Beta3 and later versions. > **NOTE**
>
> This feature is supported in DevEco Studio V3.0 Beta3 and later versions.
> >
> The component lineup that supports low-code development in eTS is now at its preliminary stage and will be expanding in coming versions. > The component lineup that supports low-code development in eTS is now at its preliminary stage and will be expanding in coming versions.
> >
...@@ -15,7 +17,7 @@ You can develop applications or services in the low-code approach using either o ...@@ -15,7 +17,7 @@ You can develop applications or services in the low-code approach using either o
- Create a project that supports low-code development. This method is used as an example in this topic. - Create a project that supports low-code development. This method is used as an example in this topic.
- In an existing project, create a .visual file for development. - In an existing project, create a .visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page).
## Creating a Project That Supports Low-Code Development ## Creating a Project That Supports Low-Code Development
......
# Getting Started with JavaScript in the Low-Code Approach # Getting Started with JavaScript in the Low-Code Approach
> **NOTE**<br/>This feature will be available in DevEco Studio V2.2 Beta1 and later versions. > **NOTE**
>
> This feature will be available in DevEco Studio V2.2 Beta1 and later versions.
> >
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development. > For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development.
...@@ -13,7 +15,7 @@ You can develop applications or services in the low-code approach using either o ...@@ -13,7 +15,7 @@ You can develop applications or services in the low-code approach using either o
- Create a project that supports low-code development. This method is used as an example in this topic. - Create a project that supports low-code development. This method is used as an example in this topic.
- In an existing project, create a Visual file for development. - In an existing project, create a Visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page).
## Creating a Project That Supports Low-Code Development ## Creating a Project That Supports Low-Code Development
......
...@@ -18,8 +18,8 @@ ...@@ -18,8 +18,8 @@
- [@ohos.application.formError](js-apis-formerror.md) - [@ohos.application.formError](js-apis-formerror.md)
- [@ohos.application.formHost](js-apis-formhost.md) - [@ohos.application.formHost](js-apis-formhost.md)
- [@ohos.application.formInfo](js-apis-formInfo.md) - [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.formProvider](js-apis-formprovider.md) - [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.ability.particleAbility](js-apis-particleAbility.md) - [@ohos.ability.particleAbility](js-apis-particleAbility.md)
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
...@@ -31,22 +31,23 @@ ...@@ -31,22 +31,23 @@
- application/[AbilityContext](js-apis-ability-context.md) - application/[AbilityContext](js-apis-ability-context.md)
- application/[abilityDelegator](js-apis-application-abilityDelegator.md) - application/[abilityDelegator](js-apis-application-abilityDelegator.md)
- application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md)
- application/[AbilityManager](js-apis-abilityManager.md)
- application/[abilityMonitor](js-apis-application-abilityMonitor.md) - application/[abilityMonitor](js-apis-application-abilityMonitor.md)
- application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md)
- application/[AbilityStageContext](js-apis-abilityStageContext.md) - application/[AbilityStageContext](js-apis-abilityStageContext.md)
- application/[Context](js-apis-application-context.md) - application/[Context](js-apis-application-context.md)
- application/[ExtensionAbilityContext](js-apis-extension-ability-context.md)
- application/[ExtensionAbilityInfo](js-apis-extensionAbilityInfo.md)
- application/[ExtensionContext](js-apis-extension-context.md) - application/[ExtensionContext](js-apis-extension-context.md)
- application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md)
- application/[FormExtensionContext](js-apis-formextensioncontext.md) - application/[FormExtensionContext](js-apis-formextensioncontext.md)
- application/[MissionInfo](js-apis-application-missionInfo.md)
- application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md)
- application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md)
- application/[ProcessRunningInfo](js-apis-processrunninginfo.md) - application/[ProcessRunningInfo](js-apis-processrunninginfo.md)
- application/[ServiceExtAbilityContext](js-apis-serviceExtAbilityContext.md)
- application/[ServiceExtensionContext](js-apis-service-extension-context.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- application/[AbilityManager (AbilityManager)](js-apis-abilityManager.md)
- application/[ExtensionAbilityContext (ExtensionAbilityContext)](js-apis-extension-ability-context.md)
- application/[ExtensionAbilityInfo (ExtensionAbilityInfo)](js-apis-extensionAbilityInfo.md)
- application/[ServiceExtAbilityContext (ServiceExtAbilityContext)](js-apis-serviceExtAbilityContext.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.commonEvent](js-apis-commonEvent.md)
...@@ -87,6 +88,7 @@ ...@@ -87,6 +88,7 @@
- [@ohos.multimedia.media](js-apis-media.md) - [@ohos.multimedia.media](js-apis-media.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- Resource Management - Resource Management
- [@ohos.i18n](js-apis-i18n.md) - [@ohos.i18n](js-apis-i18n.md)
- [@ohos.intl](js-apis-intl.md) - [@ohos.intl](js-apis-intl.md)
- [@ohos.resourceManager](js-apis-resource-manager.md) - [@ohos.resourceManager](js-apis-resource-manager.md)
...@@ -110,7 +112,6 @@ ...@@ -110,7 +112,6 @@
- [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.data.storage](js-apis-data-storage.md) - [@ohos.data.storage](js-apis-data-storage.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb/[resultSet](js-apis-data-resultset.md)
- File Management - File Management
...@@ -119,6 +120,7 @@ ...@@ -119,6 +120,7 @@
- [@ohos.environment](js-apis-environment.md) - [@ohos.environment](js-apis-environment.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.fileManager](js-apis-filemanager.md) - [@ohos.fileManager](js-apis-filemanager.md)
- [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md) - [@ohos.statfs](js-apis-statfs.md)
- [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md)
- [@ohos.volumeManager](js-apis-volumemanager.md) - [@ohos.volumeManager](js-apis-volumemanager.md)
...@@ -132,11 +134,12 @@ ...@@ -132,11 +134,12 @@
- [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.sms](js-apis-sms.md)
- [@ohos.telephony.data](js-apis-telephony-data.md) - [@ohos.telephony.data](js-apis-telephony-data.md)
- Network Management - Network Management
- [@ohos.net.connection](js-apis-net-connection.md) - [@ohos.net.connection](js-apis-net-connection.md)
- [@ohos.net.http](js-apis-http.md) - [@ohos.net.http](js-apis-http.md)
- [@ohos.request](js-apis-request.md)
- [@ohos.net.socket](js-apis-socket.md) - [@ohos.net.socket](js-apis-socket.md)
- [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md)
- [@ohos.request](js-apis-request.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.bluetooth](js-apis-bluetooth.md)
...@@ -163,6 +166,7 @@ ...@@ -163,6 +166,7 @@
- [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.screenLock](js-apis-screen-lock.md)
- [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.wallpaper](js-apis-wallpaper.md) - [@ohos.wallpaper](js-apis-wallpaper.md)
- [console (Log)](js-apis-logs.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- Device Management - Device Management
...@@ -178,6 +182,7 @@ ...@@ -178,6 +182,7 @@
- [@ohos.power](js-apis-power.md) - [@ohos.power](js-apis-power.md)
- [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md) - [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.systemParameter](js-apis-system-parameter.md)
- [@ohos.thermal](js-apis-thermal.md) - [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md) - [@ohos.update](js-apis-update.md)
...@@ -236,4 +241,3 @@ ...@@ -236,4 +241,3 @@
- [@system.sensor](js-apis-system-sensor.md) - [@system.sensor](js-apis-system-sensor.md)
- [@system.storage](js-apis-system-storage.md) - [@system.storage](js-apis-system-storage.md)
- [@system.vibrator](js-apis-system-vibrate.md) - [@system.vibrator](js-apis-system-vibrate.md)
- [console](js-apis-logs.md)
\ No newline at end of file
...@@ -32,11 +32,9 @@ Obtains the ID attached to the end of a given URI. ...@@ -32,11 +32,9 @@ Obtains the ID attached to the end of a given URI.
**Example** **Example**
```js ```js
dataUriUtils.getIdSync("com.example.dataUriUtils/1221") dataUriUtils.getId("com.example.dataUriUtils/1221")
``` ```
## dataUriUtils.attachId ## dataUriUtils.attachId
attachId(uri: string, id: number): string attachId(uri: string, id: number): string
...@@ -68,8 +66,6 @@ dataUriUtils.attachId( ...@@ -68,8 +66,6 @@ dataUriUtils.attachId(
) )
``` ```
## dataUriUtils.deleteId ## dataUriUtils.deleteId
deleteId(uri: string): string deleteId(uri: string): string
...@@ -96,8 +92,6 @@ Deletes the ID from the end of a given URI. ...@@ -96,8 +92,6 @@ Deletes the ID from the end of a given URI.
dataUriUtils.deleteId("com.example.dataUriUtils/1221") dataUriUtils.deleteId("com.example.dataUriUtils/1221")
``` ```
## dataUriUtils.updateId ## dataUriUtils.updateId
updateId(uri: string, id: number): string updateId(uri: string, id: number): string
......
...@@ -126,7 +126,7 @@ var options = { ...@@ -126,7 +126,7 @@ var options = {
windowMode: 0, windowMode: 0,
}; };
this.context.startAbility(want, options) this.context.startAbility(want, options)
.then((data) => { .then(() => {
console.log('Operation successful.') console.log('Operation successful.')
}).catch((error) => { }).catch((error) => {
console.log('Operation failed.'); console.log('Operation failed.');
...@@ -273,7 +273,7 @@ var options = { ...@@ -273,7 +273,7 @@ var options = {
}; };
var accountId = 11; var accountId = 11;
this.context.startAbility(want, accountId, options) this.context.startAbility(want, accountId, options)
.then((data) => { .then(() => {
console.log('Operation successful.') console.log('Operation successful.')
}).catch((error) => { }).catch((error) => {
console.log('Operation failed.'); console.log('Operation failed.');
...@@ -352,7 +352,7 @@ Starts an ability with **options** specified. This API uses a promise to return ...@@ -352,7 +352,7 @@ Starts an ability with **options** specified. This API uses a promise to return
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| | want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.|
| options | StartOptions | Yes| Parameters used for starting the ability.| | options | StartOptions | No | Parameters used for starting the ability.|
**Return value** **Return value**
...@@ -511,8 +511,8 @@ Terminates this ability. This API uses a promise to return the result. ...@@ -511,8 +511,8 @@ Terminates this ability. This API uses a promise to return the result.
**Example** **Example**
```js ```js
this.context.terminateSelf(want).then((data) => { this.context.terminateSelf(want).then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success:');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
...@@ -571,7 +571,7 @@ this.context.terminateSelfWithResult( ...@@ -571,7 +571,7 @@ this.context.terminateSelfWithResult(
{ {
want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"},
resultCode: 100 resultCode: 100
}).then((result) => { }).then(() => {
console.log("terminateSelfWithResult") console.log("terminateSelfWithResult")
}) })
``` ```
...@@ -595,7 +595,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to ...@@ -595,7 +595,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | ID of the connection between the two abilities.| | number | Result code of the ability connection.|
**Example** **Example**
```js ```js
...@@ -606,7 +606,7 @@ var want = { ...@@ -606,7 +606,7 @@ var want = {
} }
var options = { var options = {
onConnect: (elementName, remote) => { onConnect: (elementName, remote) => {
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote)
}, },
onDisconnect: (elementName) => { onDisconnect: (elementName) => {
console.log('connectAbility onDisconnect, elementName: ' + elementName) console.log('connectAbility onDisconnect, elementName: ' + elementName)
...@@ -615,8 +615,8 @@ var options = { ...@@ -615,8 +615,8 @@ var options = {
console.log('connectAbility onFailed, code: ' + code) console.log('connectAbility onFailed, code: ' + code)
} }
} }
this.context.connectAbility(want, options) { let result = this.context.connectAbility(want, options) {
console.log('code: ' + code) console.log('code: ' + result)
} }
``` ```
...@@ -652,7 +652,7 @@ var want = { ...@@ -652,7 +652,7 @@ var want = {
var accountId = 111; var accountId = 111;
var options = { var options = {
onConnect: (elementName, remote) => { onConnect: (elementName, remote) => {
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote)
}, },
onDisconnect: (elementName) => { onDisconnect: (elementName) => {
console.log('connectAbility onDisconnect, elementName: ' + elementName) console.log('connectAbility onDisconnect, elementName: ' + elementName)
...@@ -768,8 +768,8 @@ Sets the label of the ability in the mission. This API uses a promise to return ...@@ -768,8 +768,8 @@ Sets the label of the ability in the mission. This API uses a promise to return
**Example** **Example**
```js ```js
this.context.setMissionLabel("test").then((data) => { this.context.setMissionLabel("test").then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success:');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
......
# Ability Access Control # Ability Access Control
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import abilityAccessCtrl from '@ohos.abilityAccessCtrl' import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
``` ```
...@@ -72,6 +73,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -72,6 +73,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
Grants a user granted permission to an application. This API uses a promise to return the result. Grants a user granted permission to an application. This API uses a promise to return the result.
This is a system API.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -109,6 +112,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -109,6 +112,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. Grants a user granted permission to an application. This API uses an asynchronous callback to return the result.
This is a system API.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -139,6 +144,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -139,6 +144,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
Revokes a user granted permission given to an application. This API uses a promise to return the result. Revokes a user granted permission given to an application. This API uses a promise to return the result.
This is a system API.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -175,6 +182,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -175,6 +182,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result.
This is a system API.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
...@@ -204,6 +213,8 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g ...@@ -204,6 +213,8 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g
Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. Obtains the flags of the specified permission of a given application. This API uses a promise to return the result.
This is a system API.
**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken **System capability**: SystemCapability.Security.AccessToken
......
# Want # Want
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** The **Want** module provides the basic communication component of the system.
> 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.
**Want** is the basic communication component of the system.
> **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
``` ```
import Want from '@ohos.application.Want'; import Want from '@ohos.application.Want';
``` ```
...@@ -20,11 +19,55 @@ import Want from '@ohos.application.Want'; ...@@ -20,11 +19,55 @@ import Want from '@ohos.application.Want';
| Name | Readable/Writable| Type | Mandatory| Description | | Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | Read only | string | No | ID of the device running the ability. | | deviceId | Read only | string | No | ID of the device running the ability. |
| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| | bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| | abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. |
| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| | flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).|
| action | Read only | string | No | Action option. | | action | Read only | string | No | Action option. |
| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | | parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. |
| entities | Read only | Array\<string> | No | List of entities. | | | entities | Read only | Array\<string> | No | List of entities. |
| extensionAbilityType<sup>9+</sup> | Read only | bundle.ExtensionAbilityType | No | Type of the Extension ability. |
| extensionAbilityName<sup>9+<sup> | Read only | string | No | Description of the Extension ability name in the **Want** object. |
**Example**
- Basic usage
```js
var want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"uri": "pages/second" // uri is optional and can be used to pass the destination URI.
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
- Passing a file descriptor (FD)
```js
var fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
var want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"parameters": {
"keyFd":{"type":"FD", "value":fd}
}
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
\ No newline at end of file
...@@ -21,8 +21,8 @@ import Ability from '@ohos.application.Ability'; ...@@ -21,8 +21,8 @@ import Ability from '@ohos.application.Ability';
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| | context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.|
| launchWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters for starting the ability.| | launchWant | [Want](js-apis-application-want.md)| Yes| No| Parameters for starting the ability.|
| lastRequestWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters used when the ability was started last time.| | lastRequestWant | [Want](js-apis-application-want.md)| Yes| No| Parameters used when the ability was started last time.|
## Ability.onCreate ## Ability.onCreate
...@@ -37,7 +37,7 @@ Called to initialize the service logic when an ability is created. ...@@ -37,7 +37,7 @@ Called to initialize the service logic when an ability is created.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this ability, including the ability name and bundle name.| | want | [Want](js-apis-application-want.md)| Yes| Information related to this ability, including the ability name and bundle name.|
| param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.|
**Example** **Example**
...@@ -222,7 +222,7 @@ Called when the ability startup mode is set to singleton. ...@@ -222,7 +222,7 @@ Called when the ability startup mode is set to singleton.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-featureAbility.md#Want)| Yes| Want parameters, such as the ability name and bundle name.| | want | [Want](js-apis-application-want.md)| Yes| Want parameters, such as the ability name and bundle name.|
**Example** **Example**
......
# Brightness # Brightness
> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 Brightness module provides an API for setting the screen brightness. The Brightness module provides an API for setting the screen brightness.
> **NOTE**
>
> 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
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册