提交 c45d1f8c 编写于 作者: C chensi10 提交者: Gitee

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

Signed-off-by: Nchensi10 <chensi52@huawei.com>

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
......@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong
zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen
zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw
......@@ -520,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih
zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
......@@ -528,8 +529,13 @@ zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCreas
zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515
......
......@@ -127,7 +127,7 @@ The following table describes the subsystems of OpenHarmony. For details about t
| Build | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems |
| Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase.| All systems |
| Data Management | Provides local data management and distributed data management:<br>- Local application data management for lightweight preference databases and relational databases<br>- Distributed data service to provide applications with the capability to store data in the databases of different devices| Standard system |
| Programming Language Runtime| Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems |
| Compiler and Runtime | Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems |
| Distributed Scheduler| Starts, registers, queries, and manages system services. | All systems |
| JS UI Framework | OpenHarmony JS UI framework supports web-development-like paradigm. | All systems |
| Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables applications to use multimedia resources of the system.| All systems |
......
......@@ -17,7 +17,6 @@
- Application Package Structure
- [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md)
- [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md)
- [HAR File Structure](quick-start/har-structure.md)
- Multi-HAP Mechanism
- [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md)
- [Multi-HAP Build View](quick-start/multi-hap-build-view.md)
......@@ -49,7 +48,7 @@
- Development
- [Application Models](application-models/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md)
- [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
......@@ -57,7 +56,7 @@
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [File Management](file-management/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Telephony Service](telephony/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
......
......@@ -250,9 +250,9 @@ In the stage model, in the onWindowStageCreate lifecycle of an ability, you can
Use the API described in the table below to obtain the context associated with an ArkTS page.
| API | Description |
| :------------------------------------ | :--------------------------- |
| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.|
| API | Description |
| :------------------------------------ | :----------------------------------------------------------- |
| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.<br>Since API version 9, this API is supported in ArkTS widgets.|
**Example**
......
......@@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/Readme-EN.md)
- [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Telephony Service](telephony/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
......@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli
- [Application Test](application-test/Readme-EN.md)
- [IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- [File Management](file-management/medialibrary-overview.md)
### Tools
......
......@@ -24,13 +24,13 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O
All applications should be developed on top of these frameworks.
Then, equip yourself for developing the key features, with the following guidelines:
- [Common Event and Notification](notification/notification-overview.md)
- [Notification](notification/notification-overview.md)
- [Window Manager](windowmanager/window-overview.md)
- [WebGL](webgl/webgl-overview.md)
- [Media](media/audio-overview.md)
- [Security](security/userauth-overview.md)
- [Connectivity](connectivity/ipc-rpc-overview.md)
- [Telephony](telephony/telephony-overview.md)
- [Telephony Service](telephony/telephony-overview.md)
- [Data Management](database/database-mdds-overview.md)
- [Task Management](task-management/background-task-overview.md)
- [Device](device/usb-overview.md)
......@@ -40,6 +40,7 @@ Then, equip yourself for developing the key features, with the following guideli
- [Application Test](application-test/arkxtest-guidelines.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/napi-guidelines.md)
- [File Management](file-management/medialibrary-overview.md)
### Tools
......
......@@ -17,10 +17,11 @@
- ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility (System Applications Only)](datashareextensionability.md)
- [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md)
- [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md)
- [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md)
......@@ -34,15 +35,19 @@
- [Component Startup Rules](component-startup-rules.md)
- Inter-Device Application Component Interaction (Continuation)
- [Continuation Overview](inter-device-interaction-hop-overview.md)
- [Cross-Device Migration (System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration (System Applications Only)](hop-multi-device-collaboration.md)
- [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md)
- IPC
- [Process Model](process-model-stage.md)
- Common Events
- [Introduction to Common Events](common-event-overview.md)
- [Subscribing to Common Events](common-event-subscription.md)
- [Publishing Common Events](common-event-publish.md)
- Common Event Subscription
- [Common Event Subscription Overview](common-event-subscription-overview.md)
- [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md)
- [Subscribing to Common Events in Static Mode (for System Applications Only)](common-event-static-subscription.md)
- [Unsubscribing from Common Events](common-event-unsubscription.md)
- [Publishing Common Events](common-event-publish.md)
- [Background Services](background-services.md)
- Inter-Thread Communication
- [Thread Model](thread-model-stage.md)
......@@ -52,6 +57,7 @@
- [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and MissionList](page-mission-stack.md)
- [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md)
- [Application Configuration File](config-file-stage.md)
- FA Model Development
- [FA Model Development Overview](fa-model-development-overview.md)
......@@ -65,7 +71,7 @@
- [Creating a PageAbility](create-pageability.md)
- [Starting a Local PageAbility](start-local-pageability.md)
- [Stopping a PageAbility](stop-pageability.md)
- [Starting a Remote PageAbility (System Applications Only)](start-remote-pageability.md)
- [Starting a Remote PageAbility (for System Applications Only)](start-remote-pageability.md)
- [Starting a Specified Page](start-page.md)
- [Window Properties](window-properties.md)
- [Requesting Permissions](request-permissions.md)
......
# Using Explicit Want to Start an Ability
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used.
When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, the explicit Want is used. For details about how to use the explicit Want, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application).
## Using Explicit Want
The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application).
# Using Implicit Want to Open a Website
## Prerequisites
One or more browsers are installed on your device.
The **module.json5** of a browser application is as follows:
This section uses the operation of using a browser to open a website as an example. It is assumed that one or more browser applications are installed on the device. To ensure that the browser application can work properly, configure the [module.json5 file](../quick-start/module-configuration-file.md) as follows:
```json
"skills": [
{
"entities": [
"entity.system.browsable"
// ...
],
"actions": [
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query",
"type": "text/*"
},
{
"module": {
// ...
"abilities": [
{
"scheme": "http",
// ...
"skills": [
{
"entities": [
"entity.system.home",
"entity.system.browsable"
// ...
],
"actions": [
"action.system.home",
"ohos.want.action.viewData"
// ...
],
"uris": [
{
"scheme": "https",
"host": "www.test.com",
"port": "8080",
// Prefix matching is used.
"pathStartWith": "query",
"type": "text/*"
},
{
"scheme": "http",
// ...
}
// ...
]
}
]
}
// ...
]
},
]
}
}
```
In the initiator UIAbility, use implicit Want to start the browser application.
## How to Develop
```ts
import common from '@ohos.app.ability.common';
1. Use the custom function **implicitStartAbility** to start an ability.
```ts
async implicitStartAbility() {
try {
let want = {
// Uncomment the line below if you want to implicitly query data only in the specific bundle.
// bundleName: "com.example.myapplication",
"action": "ohos.want.action.viewData",
// entities can be omitted.
"entities": [ "entity.system.browsable" ],
"uri": "https://www.test.com:8080/query/student",
"type": "text/plain"
}
let context = getContext(this) as common.UIAbilityContext;
await context.startAbility(want)
console.info(`explicit start ability succeed`)
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`)
}
}
```
The matching process is as follows:
1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills**, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills**, the matching is successful.
function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext;
let wantInfo = {
// Uncomment the line below if you want to implicitly query data only in the specific bundle.
// bundleName: "com.example.myapplication",
"action": "ohos.want.action.viewData",
// entities can be omitted.
"entities": ["entity.system.browsable"],
"uri": "https://www.test.com:8080/query/student",
"type": "text/plain"
}
context.startAbility(wantInfo).then(() => {
// ...
}).catch((err) => {
// ...
})
}
```
3. If **uri** in the passed **want** parameter is included in **uris** under **skills**, which is concatenated into `https://www.test.com:8080/query*` (where \* is a wildcard), the matching is successful.
The matching process is as follows:
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful.
1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful.
2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful.
3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful.
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful.
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them.
When there are multiple matching applications, a dialog box is displayed for you to select one of them. The following figure shows an example.
![stage-want1](figures/stage-want1.png)
![](figures/ability-startup-with-implicit-want1.png)
\ No newline at end of file
......@@ -29,6 +29,18 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
}
}
```
4. Set **srcEntry** in the [module.json5 file](../quick-start/module-configuration-file.md) to the code path of the module.
```json
{
"module": {
"name": "entry",
"type": "entry",
"srcEntry": "./ets/myabilitystage/MyAbilityStage.ts",
// ...
}
}
```
[AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) has the lifecycle callback [onCreate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageoncreate) and the event callbacks [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant), [onConfigurationUpdated()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate), and [onMemoryLevel()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonmemorylevel).
......@@ -41,6 +53,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
- **onConfigurationUpdated()** event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) class before project configuration.
- **onMemoryLevel()** event callback: triggered when the system adjusts the memory.
When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the **onMemoryLevel()** lifecycle callback of AbilityStage to release unnecessary resources.
......@@ -54,4 +67,3 @@ When an application is switched to the background, it is cached in the backgroun
}
}
```
......@@ -15,11 +15,11 @@ Common events are classified into system common events and custom common events.
Common events are also classified into unordered, ordered, and sticky common events.
- Unordered common events: CES forwards common events based on the subscription sequence, regardless of whether subscribers receive the events.
- Unordered common events: common events that CES forwards based on the subscription sequence, regardless of whether subscribers receive the events.
- Ordered common event: CES forwards common events to the next subscriber only after receiving a reply from the previous subscriber.
- Ordered common events: common events that CES forwards based on the subscriber priority. CES forwards common events to the subscriber with lower priority only after receiving a reply from the previous subscriber with higher priority.
- Sticky common event: a public event that can be sent to a subscriber before they initiate a subscription. Only system applications or system services can send sticky common event, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
- Sticky common events: common events that can be sent to a subscriber before they initiate a subscription. Only system applications and system services can send sticky common events, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application.
......
# StaticSubscriberExtensionAbility Development
## Scenario Description
​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.**
# Subscribing to Common Events in Static Mode (for System Applications Only)
## When to Use
A static subscriber is started once it receives a target event published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. Note that this subscribing mode has negative impact on system power consumption. Therefore, exercise caution when using this mode.
## How to Develop
1. Prerequisites
The application must meet the following requirements:
The application is a system application.
The application is developed using the full SDK.
The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**.
2. Declaring a Static Subscriber
1. Declaring a Static Subscriber
To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows:
......@@ -38,7 +24,7 @@
3. Project Configuration for a Static Subscriber
2. Project Configuration for a Static Subscriber
After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows:
......@@ -70,38 +56,50 @@
Pay attention to the following fields in the JSON file:
**srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
- **srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
**type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
- **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
**metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
- **metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration.
- **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification.
- **resource**: path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
A level-2 configuration file pointed to by **metadata** must be in the following format:
A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
```ts
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows:
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows:
**name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
- **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
**permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
- **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
**events**: list of subscribed target events
- **events**: list of target events to subscribe to.
3. Device System Configuration
In the device system configuration file **/system/etc/app/install_list_capability.json**, add the bundle name of the static subscriber.
## Samples
```json
{
"install_list": [
{
"bundleName": "ohos.extension.staticSubscriber",
"allowCommonEvent": ["usual.event.A", "usual.event.B"],
}
]
}
```
For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber).
# Common Event Subscription Overview
​The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not.
- In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md).
- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from StaticSubscriberExtensionAbility. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md).
# Subscribing to Common Events
# Subscribing to Common Events in Dynamic Mode
## When to Use
You can create a subscriber object to subscribe to a common event so as to obtain the parameters passed in the event. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support).
In dynamic subscription mode, an application subscribes to a common event when it is running. If the subscribed event is published during the running period, the subscriber application will receive the event, together with the parameters passed in the event. For example, if an application expects to be notified of low battery so that it can reduce power consumption accordingly when running, then the application can subscribe to the low-battery event. Upon receiving the event, the application can close some unnecessary tasks to reduce power consumption. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support).
## Available APIs
......
# Unsubscribing from Common Events
# Unsubscribing from Common Events in Dynamic Mode
## When to Use
You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required.
You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required in dynamic mode.
## Available APIs
......@@ -21,12 +21,12 @@ You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#com
import commonEventManager from '@ohos.commonEventManager';
```
2. Subscribe to an event by following the procedure described in [Subscribing to Common Events](common-event-subscription.md).
2. Subscribe to an event by following the procedure described in [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md).
3. Call **unsubscribe** in **CommonEvent** to unsubscribe from the common event.
```ts
// The subscriber object iscreated during event subscription.
// The subscriber object is created during event subscription.
if (subscriber !== null) {
commonEventManager.unsubscribe(subscriber, (err) => {
if (err) {
......
# Using Want to Share Data Between Applications
Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications.
Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing.
## Prerequisites
1. There are two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing through **startAbility()**, the application selector is started. The system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts that application to complete data sharing.
2. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on the Want configuration used for data sharing.
3. The following actions are involved in this section:
- **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector.
- **ACTION_SEND_DATA (ohos.want.action.sendData)**: action of launching the UI for sending a single data record. It is used to transfer data to the shared party.
## How to Develop
- Sharing party
1. In the stage mode, the [File Descriptor (FD)](../reference/apis/js-apis-fileio.md#fileioopensync) is used for file transfer. This example assumes that the path of the file to share is obtained.
```ts
import fileIO from '@ohos.fileio';
// let path = ...
// Open the file whose path is a variable.
let fileFd = fileIO.openSync(path, 0o102, 0o666);
```
2. As described in the prerequisites, the sharing party starts an application selector and shares the data to the selector, and the selector transfers the data to the shared party. Want of the sharing party must be nested at two layers. At the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. At the second layer, complete Want is declared in the custom field **parameters** to transfer the data to share.
```ts
import wantConstant from '@ohos.app.ability.wantConstant';
// let path = ...
// let fileFd = ...
// let fileSize = ...
let want = {
/ This action is used to implicitly match the application selector.
action: wantConstant.Action.ACTION_SELECT,
// This is the custom parameter in the first layer of Want,
/ which is intended to add information to the application selector.
parameters: {
// MIME type of PDF.
"ability.picker.type": "application/pdf",
"ability.picker.fileNames": [path],
"ability.picker.fileSizes": [fileSize],
// This nested Want ,which will be directly sent to the selected application.
"ability.want.params.INTENT": {
"action": "ohos.want.action.sendData",
"type": "application/pdf",
"parameters": {
"keyFd": {"type": "FD", "value": fileFd}
}
}
}
In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing.
The following actions are involved for data sharing:
- **ohos.want.action.select**: action of starting the application selector.
- **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party.
## Sharing Party
The sharing party starts an application selector and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. In the second layer, the data to share is declared
in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application selector. The shared party obtains the shared data from **parameters**.
```ts
import common from '@ohos.app.ability.common';
let fileType = 'application/pdf';
let fileName = 'TestFile.pdf';
let fileFd = -1; // Obtain the file descriptor (FD) of the file to share.
let fileSize; // Obtain the size of the file to share.
function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext;
let wantInfo = {
/ This action is used to implicitly match the application selector.
action: 'ohos.want.action.select',
// This is the custom parameter in the first layer of Want,
/ which is intended to add information to the application selector.
parameters: {
// MIME type of PDF.
"ability.picker.type": fileType,
"ability.picker.fileNames": [fileName],
"ability.picker.fileSizes": [fileSize],
// This is nested Want ,which will be directly sent to the selected application.
"ability.want.params.INTENT": {
"action": "ohos.want.action.sendData",
"type": "application/pdf",
"parameters": {
"keyFd": { "type": "FD", "value": fileFd }
}
}
```
In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved:
- **"ability.picker.type"**: The application selector renders the file type icon based on this field.
- **"ability.picker.fileNames"**: The application selector displays the file name based on this field.
- **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte.
- **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping.
For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows:
![stage-want2](figures/stage-want2.png)
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
- Shared party
1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows:
```ts
"skills": [
{
"entities": [
}
}
context.startAbility(wantInfo).then(() => {
// ...
}).catch((err) => {
// ...
})
}
```
> **NOTE**
>
> Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md).
In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application selector:
- **ability.picker.type**: file type icon.
- **ability.picker.fileNames**: file name.
- **ability.picker.fileSizes**: file size, in bytes.
- **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping.
The following figure shows an example.
![](figures/ability-startup-with-implicit-want2.png)
## Shared Party
To enable the shared party to identify the shared content, configure **skills** in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility of the shared party. The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT** of the sharing party, respectively.
```json
{
"module": {
// ...
"abilities": [
{
// ...
"skills": [
{
// ...
],
"actions": [
"actions": [
"action.system.home",
"ohos.want.action.sendData"
// ...
],
"uris": [
{
"type": "application/pdf"
},
// ...
]
},
]
```
The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT**, respectively.
Files can be transferred in FD mode, but not URI mode. In implicit matching, the **type** field in Want must match the **type** field in **uris** under **skills** of the shared party. Therefore, specify only the **type** field in **uris**. If **host** and **port** are specified, the matching fails. The application selector initiates implicit matching based on **ability.want.params.INTENT**. Therefore, when the **uri** field added to **ability.want.params.INTENT** matches the **uris** field under **skills**, the matching is successful and additional data can be transferred.
2. After the application selector starts the shared party, the system calls **onCreate** and passes **ability.want.params.INTENT** to the **want** parameter.
```ts
onCreate(want, launchParam) {
// When keyFd is undefined, the application crashes.
if (want["parameters"]["keyFd"] !== undefined) {
// Receive the file descriptor.
let fd = want["parameters"]["keyFd"].value;
// ...
}
],
"uris": [
{
"type": "application/pdf"
},
]
}
]
}
```
]
}
}
```
After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want.
The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations.
```json
{
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry",
"uri": "",
"type": "application/pdf",
"flags": 0,
"action": "ohos.want.action.sendData",
"parameters": {
"component.startup.newRules": true,
"keyFd": {
"type": "FD",
"value": 36
},
"mime-type": "application/pdf",
"moduleName": "entry",
"ohos.aafwk.param.callerPid": 3488,
"ohos.aafwk.param.callerToken": 537379209,
"ohos.aafwk.param.callerUid": 20010014
},
"entities": []
}
```
# DataShareExtensionAbility (System Applications Only)
# DataShareExtensionAbility (for System Applications Only)
DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
# EnterpriseAdminExtensionAbility Development
## Introduction
## Introduction to EnterpriseAdminExtensionAbility
**EnterpriseAdminExtensionAbility** is essential to a mobile device management (MDM) application. When developing an MDM application for an enterprise, you must inherit the **EnterpriseAdminExtensionAbility** class and have the MDM service logic implemented in an **EnterpriseAdminExtensionAbility** instance. The **EnterpriseAdminExtensionAbility** class provides callbacks for the enable, disable, install, and uninstall events of a device administrator application, implementing notification of system administrator status changes.
EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Management (MDM) applications. When developing MDM applications for enterprises, you need to inherit EnterpriseAdminExtensionAbility and implement MDM service logic in the EnterpriseAdminExtensionAbility instance. EnterpriseAdminExtensionAbility implements notifications of system management status changes and defines the callbacks for when a device administrator application is enabled or disabled or an application is installed or uninstalled.
## Constraints
- ***Function constraints***
- **Function constraints**
The APIs provided can be used only by device administrator applications.
EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application
## Observing Activation/Deactivation of a Device Administrator Application and Installation/Removal of an Application
### Overview
**onAdminEnabled**: called when the enterprise administrator or employee deploys an MDM application and enables the DeviceAdmin permission for the application. The MDM application can set the initialization policy in the **onAdminEnabled** callback.
**onAdminEnabled**: When an enterprise administrator or employee deploys an MDM application and activates the device administrator application, this callback is invoked to notify the MDM application that the DeviceAdmin permission is activated. The initialization policy of the MDM application can set in **onAdminEnabled**.
**onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed.
**onAdminDisabled**: When the device administrator application is deactivated, the callback is invoked to notify the MDM application that the DeviceAdmin permission is deactivated.
**onBundleAdded**: called to notify the enterprise administrator that the specified MDM application is installed on the device. In enterprise application administration settings, after the enterprise administrator subscribes to application installation and uninstallation events, the MDM application reports the events through the callbacks.
**onBundleAdded**: The enterprise administrator can subscribe to application installation and uninstallation events. When an application is installed on an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device.
**onBundleRemoved**: When an application is removed from an enterprise device, the MDM application reports the event in this callback to notify the enterprise administrator.
### Available APIs
| Class | API | Description |
| Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. |
| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when a device administrator application is deactivated.|
| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when an application is installed on a device. |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when a device administrator application is activated. |
| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when an application is removed from a device. |
### How to Develop
To implement **EnterpriseAdminExtensionAbility**, enable the device administrator application and create an **ExtensionAbility** instance from the code directory of the device administrator application. The procedure is as follows:
To implement EnterpriseAdminExtensionAbility, you need to activate the device administrator application and create **ExtensionAbility** in the code directory of the device administrator application. The procedure is as follows:
1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
2. Right-click the **EnterpriseExtAbility** directory and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, through which the enterprise administrator can receive notification when the device administrator application is enabled or disabled.
2. Right-click the **EnterpriseExtAbility** directory, and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Inherit the **EnterpriseAdminExtensionAbility** module to the custom class and add application notification callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**. When the device administrator application is activated or deactivated, the device administrator can receive notifications.
```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
console.info("onAdminEnabled");
}
onAdminDisabled() {
console.info("onAdminDisabled");
}
......@@ -56,14 +56,14 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
onBundleAdded(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
}
onBundleRemoved(bundleName: string) {
console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName)
}
};
```
4. Register **ServiceExtensionAbility** in the [module.json5](../quick-start/module-configuration-file.md) file of the target module. Among the parameters, set **type** to **enterpriseAdmin** and **srcEntrance** to the code path of the current ExtensionAbility.
4. Register **ServiceExtensionAbility** in the [**module.json5**](../quick-start/module-configuration-file.md) file corresponding to the project module. Set **type** to **enterpriseAdmin** and **srcEntrance** to the path of the ExtensionAbility code.
```ts
"extensionAbilities": [
......@@ -78,7 +78,7 @@ To implement **EnterpriseAdminExtensionAbility**, enable the device administrato
## Example
Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **@ohos.enterprise.adminManager** module to subscribe to and unsubscribe from the application installation and uninstallation event, respectively. After the subscription is successful, the MDM application notifies the enterprise administrator when it is installed or uninstalled on the device.
Use **subscribeManagedEvent()** and **unsubscribeManagedEvent()** in the **@ohos.enterprise.adminManager** module to subscribe to application installation and removal events. When an application is installed or removed, the MDM application is notified of the event. Then, the MDM application reports the event in the callback to notify the enterprise administrator.
```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
......@@ -108,4 +108,3 @@ Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **
}
```
# Cross-Device Migration (System Applications Only)]
# Cross-Device Migration (for System Applications Only)]
## When to Use
......
# Multi-device Collaboration (System Applications Only)
# Multi-device Collaboration (for System Applications Only)
## When to Use
......@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-system-applications-only).
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call.
......@@ -319,10 +319,10 @@ The following describes how to implement multi-device collaboration through cros
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;| Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.|
| on(type:&nbsp;"release",&nbsp;callback:&nbsp;OnReleaseCallback):&nbsp;void | Callback invoked when the caller object is released.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
### How to Develop
......@@ -348,16 +348,15 @@ The following describes how to implement multi-device collaboration through cros
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description|
| -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
| JSON Field| Description|
| -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
An example of the UIAbility configuration is as follows:
An example of the UIAbility configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
......@@ -369,19 +368,18 @@ The following describes how to implement multi-device collaboration through cros
"visible": true
}]
```
2. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
```
3. Define the agreed sequenceable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts
export default class MySequenceable {
export default class MyParcelable {
num: number = 0;
str: string = "";
......@@ -390,71 +388,69 @@ The following describes how to implement multi-device collaboration through cros
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
```
4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) {
console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
onCreate(want, launchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
}
}
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD);
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
}
}
}
```
```ts
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
function sendMsgCallback(data) {
console.info('CalleeSortFunc called');
// Obtain the parcelable data sent by the caller ability.
let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the parcelable data result to the caller ability.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
onCreate(want, launchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
}
}
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD);
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
}
}
}
```
4. Obtain the caller object and access the callee ability.
1. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
```
2. Obtain the caller object.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
```ts
async onButtonGetRemoteCaller() {
......@@ -483,14 +479,14 @@ The following describes how to implement multi-device collaboration through cros
For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
5. Sends agreed sequenceable data to the callee ability.
1. The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability.
5. Sends agreed parcelable data to the callee ability.
1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability.
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg';
async onButtonCall() {
try {
let msg = new MySequenceable(1, 'origin_Msg');
let msg = new MyParcelable(1, 'origin_Msg');
await this.caller.call(MSG_SEND_METHOD, msg);
} catch (error) {
console.info(`caller call failed with ${error}`);
......@@ -505,12 +501,12 @@ The following describes how to implement multi-device collaboration through cros
backMsg: string = '';
async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MySequenceable(1, originMsg);
let msg = new MyParcelable(1, originMsg);
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg);
console.info('caller callWithResult succeed');
let result = new MySequenceable(0, '');
data.readSequenceable(result);
let result = new MyParcelable(0, '');
data.readParcelable(result);
backMsg(result.str);
console.info(`caller result is [${result.num}, ${result.str}]`);
} catch (error) {
......@@ -521,8 +517,8 @@ The following describes how to implement multi-device collaboration through cros
6. Release the caller object.
When the caller object is no longer required, use **release()** to release it.
When the caller object is no longer required, use **release()** to release it.
```ts
releaseCall() {
try {
......
# InputMethodExtensionAbility Development
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) is an ExtensionAbility component of the inputMethod type that provides extension capabilities for the input method framework.
InputMethodExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller.
InputMethodExtensionAbility provides related capabilities through the [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md).
## Implementing an Input Method Application
InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required.
- **onCreate**
This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener.
> **NOTE**
>
> If a service has been created, starting it again does not trigger the **onCreate()** callback.
- **onDestroy**
This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener.
## How to Develop
To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows:
In the **ets** directory of the target module, right-click and choose **New** > **Extention Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility.
> **NOTE**
>
> When compiling the input method application, use the signature at the system_core level. Otherwise, the application will not be able to start the keyboard.
The minimum template implements an input method application with the most basic features, such as starting the keyboard, entering text, and deleting input. You can diversify the feature set of the application by, for example, adding the feature to hide the keyboard.
The minimum template contains four files: **KeyboardController.ts**, **InputMethodService.ts**, **Index.ets**, and **KeyboardKeyData.ts**. The file directory is as follows:
```
/src/main/
├── ets/inputmethodextability
│ └──model/KeyboardController.ts # Shows the keyboard.
│ └──InputMethodService.ts # Customizes a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks.
│ └──pages
│ └── Index.ets # Draws the keyboard and adds the input and deletion features.
│ └── KeyboardKeyData.ts # Defines keyboard attributes.
├── resources/base/profile/main_pages.json
```
## File Introduction
1. **InputMethodService.ts** file:
In this file, add the dependency package for importing InputMethodExtensionAbility. Customize a class that inherits from InputMethodExtensionAbility and add the required lifecycle callbacks.
```ts
import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility';
import { KeyboardController } from './model/KeyboardController'
export default class InputDemoService extends InputMethodExtensionAbility {
private keyboardController: KeyboardController;
onCreate(want) {
this.keyboardController = new KeyboardController(this.context);
this.keyboardController.onCreate(); // Initialize the window and register an event listener for the input method framework.
}
onDestroy() {
console.log("onDestroy.");
this.context.destroy();
}
}
```
2. **KeyboardController.ts** file:
```ts
import inputMethodEngine from '@ohos.inputMethodEngine';
import display from '@ohos.display';
import windowManager from '@ohos.window';
// Call the getInputMethodAbility API to obtain an instance, and then call the other APIs of the input method framework based on the instance.
globalThis.inputAbility = inputMethodEngine.getInputMethodAbility();
export class KeyboardController {
mContext; // Save the context attribute in InputMethodExtensionAbility.
WINDOW_TYPE_INPUT_METHOD_FLOAT = 2105; // Define the window type. The value 2105 indicates the input method window type, which is used to create an input method application window.
windowName = 'inputApp';
private windowHeight: number = 0;
private windowWidth: number = 0;
private nonBarPosition: number = 0;
private isWindowShowing: boolean = false;
constructor(context) {
this.mContext = context;
}
public onCreate(): void
{
this.initWindow(); // Initialize the window.
this.registerListener(); // Register an event listener for the input method framework.
}
public onDestroy(): void // Destroy the instance.
{
this.unRegisterListener(); // Deregister the event listener.
let win = windowManager.findWindow(this.windowName);
win.destroyWindow(); // Destroy the window.
this.mContext.terminateSelf(); // Terminate the InputMethodExtensionAbility service.
}
private initWindow(): void // Initialize the window.
{
let dis = display.getDefaultDisplaySync();
let dWidth = dis.width;
let dHeight = dis.height;
let keyHeightRate = 0.47;
let keyHeight = dHeight * keyHeightRate;
this.windowWidth = dWidth;
this.windowHeight = keyHeight;
this.nonBarPosition = dHeight - keyHeight;
let config = {
name: this.windowName,
windowType: this.WINDOW_TYPE_INPUT_METHOD_FLOAT,
ctx: this.mContext
}
windowManager.createWindow(config).then((win) => { // Create a window of the specified type.
win.resize(dWidth, keyHeight).then(() => {
win.moveWindowTo(0, this.nonBarPosition).then(() => {
win.setUIContent('pages/InputMethodExtAbility/Index').then(() => {
});
});
});
});
}
private registerListener(): void
{
this.registerInputListener(); // Register an event listener for the input method framework service.
globalThis.inputAbility.on('keyboardShow', () => {// Register an event listener for the keyboard .
if (this.isWindowShowing) {
return;
}
this.isWindowShowing = true;
this.showHighWindow(); // Show the window.
});
...
// Register a listener for keyboard hiding.
}
private registerInputListener() { // Register a listener for the enabling and disabling events of the input method framework service.
globalThis.inputAbility.on('inputStart', (kbController, textInputClient) => {
globalThis.textInputClient = textInputClient; // This is an input method client instance, based on which you can call the functional APIs that the input method framework provides for the input method application.
globalThis.keyboardController = kbController;
})
globalThis.inputAbility.on('inputStop', (imeId) => {
if (imeId == "Bundle name/Ability name") {
this.onDestroy();
}
});
}
private unRegisterListener(): void
{
globalThis.inputAbility.off('inputStart');
globalThis.inputAbility.off('inputStop', () => {});
globalThis.inputAbility.off('keyboardShow');
}
private showHighWindow() {
let win = windowManager.findWindow(this.windowName)
win.resize(this.windowWidth, this.windowHeight).then(() => {
win.moveWindowTo(0, this.nonBarPosition).then(() => {
win.showWindow().then(() => {
this.isWindowShowing = false;
})
})
})
}
}
```
3. **KeyboardKeyData.ts** file:
In this file you can define the content displayed on the soft keyboard.
```ts
export interface sourceListType {
content: string,
}
export let numberSourceListData: sourceListType[] = [
{
content: '1'
},
{
content: '2'
},
{
content: '3'
},
{
content: '4'
},
{
content: '5'
},
{
content: '6'
},
{
content: '7'
},
{
content: '8'
},
{
content: '9'
},
{
content: '0'
}
]
```
4. **Index.ets** file:
This file describes the functions of keys. For example, the number keys print numbers in the text box, and the delete key deletes what's entered.
Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file.
```ets
import { numberSourceListData, sourceListType } from './keyboardKeyData'
@Component
struct keyItem {
private keyValue: sourceListType
@State keyBgc: string = "#fff"
@State keyFontColor: string = "#000"
build() {
Column() {
Flex({ direction: FlexDirection.Column,
alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(this.keyValue.content).fontSize(20).fontColor(this.keyFontColor)
}
}
.backgroundColor(this.keyBgc)
.borderRadius(6)
.width("8%")
.height("65%")
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
globalThis.textInputClient.insertText(this.keyValue.content);
}
})
}
}
// Component used for deletion.
@Component
export struct deleteItem {
@State keyBgc: string = "#fff"
@State keyFontColor: string = "#000"
build() {
Column() {
Flex({ direction: FlexDirection.Column,
alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text("Delete").fontSize(20).fontColor(this.keyFontColor)
}
}
.backgroundColor(this.keyBgc)
.width("13%")
.borderRadius(6)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
globalThis.textInputClient.deleteForward(1);
}
})
}
}
// Numeric keyboard
@Component
struct numberMenu {
private numberList: sourceListType[]
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) {
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.numberList, (item: sourceListType) => { // First row on the numeric keyboard
keyItem({ keyValue: item })
}, (item: sourceListType) => item.content);
}
.padding({ top: "2%" })
.width("96%")
.height("25%")
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
deleteItem()
}
.width("96%")
.height("25%")
}
}
}
@Entry
@Component
struct Index {
private numberList: sourceListType[] = numberSourceListData
build() {
Stack() {
Flex({
direction: FlexDirection.Column,
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.End
}) {
Flex({
direction: FlexDirection.Column,
alignItems: ItemAlign.Center,
justifyContent: FlexAlign.SpaceBetween
}) {
numberMenu({
numberList: this.numberList
})
}
.align(Alignment.End)
.width("100%")
.height("75%")
}
.height("100%").align(Alignment.End).backgroundColor("#cdd0d7")
}
.position({ x: 0, y: 0 }).zIndex(99999)
}
}
```
Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntrance** to the code path of the InputMethodExtensionAbility component.
```ts
{
"module": {
// ...
"extensionAbilities": [
{
"description": "inputMethod",
"icon": "$media:icon",
"name": "InputMethodExtAbility",
"srcEntrance": "./ets/inputmethodextability/InputMethodService.ts",
"type": "inputMethod",
"visible": true,
}
]
}
}
```
......@@ -18,7 +18,7 @@ To develop the Worker mode, perform the following steps:
}
```
2. Create the **worker.js** file based on the configuration in **build-profile.json5**.
2. Create the **worker.ts** file based on the configuration in **build-profile.json5**.
```ts
import worker from '@ohos.worker';
......@@ -58,7 +58,7 @@ To develop the Worker mode, perform the following steps:
```ts
import worker from '@ohos.worker';
let wk = new worker.ThreadWorker("../workers/worker.js");
let wk = new worker.ThreadWorker("../workers/worker.ts");
// Send a message to the worker thread.
wk.postMessage("message from main thread.")
......@@ -74,6 +74,6 @@ To develop the Worker mode, perform the following steps:
> **NOTE**
>
> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.js** when creating a worker thread in the FA model.
> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model.
>
> - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types).
# Setting the Icon and Name of a Mission Snapshot
Setting a unique icon and name for each mission snapshot of an application helps you better manage the missions and functions of the application.
By default, the **icon** and **label** fields in the [abilities tag](../quick-start/module-configuration-file.md#abilities) of the [module.json5 file](../quick-start/module-configuration-file.md) are used to set the icon and label.
Figure 1 Mission snapshot of a UIAbility
![](figures/mission-list-recent.png)
You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) and [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to customize the icon and name for a mission snapshot. For example, for a UIAbility instance with the launch type set to **standard**, you can configure the icon and name for each mission snapshot based on different functions.
This document describes the following operations:
- [Setting a Mission Snapshot Icon (for System Applications Only)](#setting-a-mission-snapshot-icon-for-system-applications-only)
- [Setting a Mission Snapshot Name](#setting-a-mission-snapshot-name)
## Setting a Mission Snapshot Icon (for System Applications Only)
Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
this.context.setMissionIcon(imagePixelMap, (err) => {
console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`);
})
```
The display effect is shown below.
Figure 2 Mission snapshot icon
![](figures/mission-set-task-snapshot-icon.png)
## Setting a Mission Snapshot Name
Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot.
```ts
this.context.setMissionLabel('test').then(() => {
console.info('setMissionLabel succeeded.');
}).catch((err) => {
console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`);
});
```
The display effect is shown below.
Figure 3 Mission snapshot name
![](figures/mission-set-task-snapshot-label.png)
\ No newline at end of file
......@@ -18,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [
This topic describes how to use ServiceExtensionAbility in the following scenarios:
- [Implementing a Background Service (System Applications Only)](#implementing-a-background-service-system-applications-only)
- [Implementing a Background Service (for System Applications Only)](#implementing-a-background-service-for-system-applications-only)
- [Starting a Background Service (System Applications Only)](#starting-a-background-service-system-applications-only)
- [Starting a Background Service (for System Applications Only)](#starting-a-background-service-for-system-applications-only)
- [Connecting to a Background Service](#connecting-to-a-background-service)
......@@ -33,7 +33,7 @@ This topic describes how to use ServiceExtensionAbility in the following scenari
> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground.
## Implementing a Background Service (System Applications Only)
## Implementing a Background Service (for System Applications Only)
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
......@@ -164,7 +164,7 @@ To implement a background service, manually create a ServiceExtensionAbility com
```
## Starting a Background Service (System Applications Only)
## Starting a Background Service (for System Applications Only)
A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
......
# Starting a Remote PageAbility (System Applications Only)
# Starting a Remote PageAbility (for System Applications Only)
The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
......
# Subscribing to System Environment Variable Changes
System environment variables are system settings (for example, the system language or screen direction) of a device that may change during the running of an application.
By subscribing to the changes of system environment variables, the application can detect the changes in a timely manner and process the changes accordingly, providing better user experience. For example, when the system language changes, the application can display the UI in the new language; when the user rotates the device to landscape or portrait mode, the application can re-arrange the UI to adapt to the new screen orientation and size.
The system environment variable changes are usually triggered by options in **Settings** or icons in **Control Panel**. For details about the system environment variables that support subscription, see [Configuration](../reference/apis/js-apis-app-ability-configuration.md).
In OpenHarmony, you can subscribe to system environment variable changes in the following ways:
- [Using ApplicationContext for Subscription](#using-applicationcontext-for-subscription)
- [Using AbilityStage for Subscription](#using-abilitystage-for-subscription)
- [Using UIAbility for Subscription](#using-uiability-for-subscription)
- [Using ExtensionAbility for Subscription](#using-extensionability-for-subscription)
## Using ApplicationContext for Subscription
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides an API for registering a callback function to subscribe to the system environment variable changes. It also provides an API for deregistration so you can release related resources when they are no longer needed.
1. Call **ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)** to subscribe to changes in system environment variables. The code snippet below is used to subscribe to system language changes on a page.
```ts
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // ID of the subscription for system environment variable changes.
subscribeConfigurationUpdate() {
let systemLanguage: string = this.context.config.language; // Obtain the system language in use.
// 1. Obtain an ApplicationContext object.
let applicationContext = this.context.getApplicationContext();
// 2. Subscribe to system environment variable changes through ApplicationContext.
let environmentCallback = {
onConfigurationUpdated(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (this.systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
},
onMemoryLevel(level) {
console.info(`onMemoryLevel level: ${level}`);
}
}
this.callbackId = applicationContext.on('environment', environmentCallback);
}
// Page display.
build() {
// ...
}
}
```
2. Call **ApplicationContext.off(type: 'environment', callbackId: number)** to release the resources.
```ts
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
private context = getContext(this) as common.UIAbilityContext;
private callbackId: number; // ID of the subscription for system environment variable changes.
unsubscribeConfigurationUpdate() {
let applicationContext = this.context.getApplicationContext();
applicationContext.off('environment', this.callbackId);
}
// Page display.
build() {
// ...
}
}
```
## Using AbilityStage for Subscription
The AbilityStage component provides the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object.
> **NOTE**
>
> - AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
> - The callback used to subscribe to system environment variable changes has the same lifecycle as the [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) instance and will be destroyed when the instance is destroyed.
The code snippet below uses the [AbilityStage.onConfigurationUpdate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate) callback to subscribe to the system language changes.
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
let systemLanguage: string; // System language in use.
export default class MyAbilityStage extends AbilityStage {
onCreate() {
systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time.
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
}
}
```
## Using UIAbility for Subscription
The UIAbility component provides the **UIAbility.onConfigurationUpdate()** callback for subscribing to system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object, without restarting the UIAbility.
> **NOTE**
>
> The callback used to subscribe to system environment variable changes has the same lifecycle as the UIAbility instance and will be destroyed when the instance is destroyed.
The code snippet below uses the **onConfigurationUpdate()** callback to subscribe to the system language changes.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
let systemLanguage: string; // System language in use.
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time.
console.info(`systemLanguage is ${systemLanguage} `);
}
onConfigurationUpdate(newConfig) {
console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
if (systemLanguage !== newConfig.language) {
console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison.
}
}
// ...
}
```
## Using ExtensionAbility for Subscription
The ExtensionAbility component provides the **onConfigurationUpdate()** callback for subscribing system environment variable changes. This callback is invoked when a system environment variable changes. In this callback, the latest system environment configuration is obtained through the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) object.
> **NOTE**
>
> The callback used to subscribe to system environment variable changes has the same lifecycle as the ExtensionAbility instance and will be destroyed when the instance is destroyed.
The code snippet below uses FormExtensionAbility as an example to describe how to use the **onConfigurationUpdate()** callback to subscribe to system environment variable changes.
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class EntryFormAbility extends FormExtensionAbility {
onConfigurationUpdate(newConfig) {
console.info(`newConfig is ${JSON.stringify(newConfig)}`);
}
// ...
}
```
......@@ -15,9 +15,11 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result)
- [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only)
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
- [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only)
## Starting UIAbility in the Same Application
......@@ -202,8 +204,7 @@ This section describes how to start the UIAbility of another application through
```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
![](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
......@@ -307,6 +308,55 @@ If you want to obtain the return result when using implicit Want to start the UI
})
```
## Starting UIAbility with Window Mode Specified (for System Applications Only)
By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen.
In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI.
In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time.
In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency.
The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).
> **NOTE**
>
> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities tag](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported.
The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page.
1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).
2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window.
For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional.
parameters: {// Custom information.
info: 'From the Index page of EntryAbility',
},
}
let options = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
}
// context is the ability-level context of the initiator UIAbility.
this.context.startAbility(wantInfo, options).then(() => {
// ...
}).catch((err) => {
// ...
})
```
The display effect is shown below.
![](figures/start-uiability-floating-window.png)
## Starting a Specified Page of UIAbility
......@@ -422,7 +472,7 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
## Using Ability Call to Implement UIAbility Interaction (for System Applications Only)
Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC.
......@@ -449,9 +499,9 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process.
Figure 1 Ability call process
Figure 1 Ability call process
![call](figures/call.png)
![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
......@@ -476,8 +526,8 @@ The following table describes the main APIs used for the ability call. For detai
| startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
......@@ -495,37 +545,39 @@ For the callee ability, implement the callback to receive data and the methods t
1. Configure the ability launch type.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description|
| -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
}]
```
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
}]
```
2. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
```
3. Define the agreed sequenceable data.
3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string.
```ts
export default class MySequenceable {
export default class MyParcelable {
num: number = 0
str: string = ""
......@@ -534,15 +586,15 @@ For the callee ability, implement the callback to receive data and the methods t
this.str = string
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num)
messageParcel.writeString(this.str)
marshalling(messageSequence) {
messageSequence.writeInt(this.num)
messageSequence.writeString(this.str)
return true
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt()
this.str = messageParcel.readString()
unmarshalling(messageSequence) {
this.num = messageSequence.readInt()
this.str = messageSequence.readString()
return true
}
}
......@@ -550,8 +602,7 @@ For the callee ability, implement the callback to receive data and the methods t
4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
......@@ -559,14 +610,14 @@ For the callee ability, implement the callback to receive data and the methods t
function sendMsgCallback(data) {
console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData);
// Obtain the parcelable data sent by the caller ability.
let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
// Return the parcelable data result to the caller ability.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
......@@ -588,7 +639,6 @@ For the callee ability, implement the callback to receive data and the methods t
}
```
### Accessing the Callee Ability
1. Import the **UIAbility** module.
......@@ -598,9 +648,9 @@ For the callee ability, implement the callback to receive data and the methods t
```
2. Obtain the caller interface.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements.
```ts
// Register the onRelease() listener of the caller ability.
private regOnRelease(caller) {
......
......@@ -17,13 +17,10 @@ The launch type of the UIAbility component refers to the state of the UIAbility
Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**.
**Figure 1** Demonstration effect in singleton mode
**Figure 1** Demonstration effect in singleton mode
![uiability-launch-type1](figures/uiability-launch-type1.png)
![uiability-launch-type1](figures/uiability-launch-type1.png)
> **NOTE**
>
> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> **NOTE**<br>Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**.
......@@ -47,9 +44,8 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration
In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**.
**Figure 2** Demonstration effect in standard mode
![standard-mode](figures/standard-mode.png)
**Figure 2** Demonstration effect in standard mode
![standard-mode](figures/standard-mode.png)
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
......@@ -73,14 +69,13 @@ To use the standard mode, set **launchType** in the [module.json5 configuration
The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document.
**Figure 3** Demonstration effect in specified mode
**Figure 3** Demonstration effect in specified mode
![uiability-launch-type2](figures/uiability-launch-type2.png)
![uiability-launch-type2](figures/uiability-launch-type2.png)
For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility.
For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility.
1. In SpecifiedAbility, set the **launchType** field in the [module.json5 file](../quick-start/module-configuration-file.md) to **specified**.
1. In SpecifiedAbility, set the **launchType** field in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **specified**.
```json
{
"module": {
......@@ -95,9 +90,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
}
```
2. Before a UIAbility instance is created, you can create a unique string key for the instance. The key is bound to the UIAbility instance when it is created. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application is asked which UIAbility instance is used to respond to the [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) request.
In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances.
2. Create a unique string key for the instance. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application, based on the key, identifies the UIAbility instance used to respond to the request. In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance.
```ts
// Configure an independent key for each UIAbility instance.
// For example, in the document usage scenario, use the document path as the key.
......@@ -121,10 +115,11 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
// ...
})
```
3. During running, the internal service of UIAbility determines whether to create multiple instances. If the key is matched, the UIAbility instance bound to the key is started. Otherwise, a new UIAbility instance is created.
The launch type of SpecifiedAbility is set to **specified**. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to parse the input **want** parameter and obtain the custom parameter **instanceKey**. A string key identifier is returned through the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the AbilityStage instance. [If the returned key corresponds to a started UIAbility instance](mission-management-launch-type.md#fig14520125175314), that UIAbility instance is switched to the foreground and gains focus again. Otherwise, a new instance is created and started.
3. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to obtain the key of the UIAbility, because the launch type of SpecifiedAbility is set to **specified**. If a UIAbility instance matching the key exists, the system starts the UIAbility instance and invokes its [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback. Otherwise, the system creates a new UIAbility instance and invokes its [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks.
In the sample code, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback parses the **want** parameter to obtain the custom parameter **instanceKey**. The service logic returns a key string based on **instanceKey** parameter to identify the UIAbility instance. If the returned key maps to a started UIAbility instance, the system pulls the UIAbility instance back to the foreground and obtains the focus. If the returned key does not map to a started UIAbility instance, the system creates a new UIAbility instance and starts it.
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
......@@ -133,7 +128,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
// In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified.
// In this example, SpecifiedAbility of module1 is returned.
if (want.abilityName === 'SpecifiedAbility') {
// The returned string key is a custom string.
// The returned key string is a custom string.
return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`;
}
......@@ -141,22 +136,17 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of
}
}
```
> **NOTE**
> **NOTE**<br>
>
> 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example.
For example, in the document application, different keys are bound to different document instances. Each time a document is created, a new key (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage.
The following steps are used as an example.
1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started.
2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2.
3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3.
4. Return to the home screen and open file A again. UIAbility instance 2 is started.
<!--no_check-->
\ No newline at end of file
4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance.
......@@ -14,7 +14,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat
>
## Setting an Embedded Ability (System Applications Only)
## Setting an Embedded Ability (for System Applications Only)
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
......@@ -78,7 +78,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i
```
## Starting an Embedded Ability (System Applications Only)
## Starting an Embedded Ability (for System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent.
......
......@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest'
import {Driver,ON,Component,MatchPattern} from '@ohos.uitest'
```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
......@@ -131,16 +131,16 @@ export default function abilityTest() {
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
//ui test code
//init uidriver
var driver = await UiDriver.create();
//init driver
var driver = await Driver.create();
await driver.delayMs(1000);
//find button by text 'Next'
var button = await driver.findComponent(BY.text('Next'));
//find button on text 'Next'
var button = await driver.findComponent(ON.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
//check text
await driver.assertComponentExist(BY.text('after click'));
await driver.assertComponentExist(ON.text('after click'));
await driver.pressBack();
done();
})
......@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands**
> Configure hdc-related environment variables, and then perform the following:
> Before running commands in the CLI, make sure hdc-related environment variables have been configured.
- Open the CLI.
- Run the **aa test** commands.
......
......@@ -5,6 +5,10 @@
- [HTTP Data Request](http-request.md)
- [WebSocket Connection](websocket-connection.md)
- [Socket Connection](socket-connection.md)
- [Network Policy Management](net-policy-management.md)
- [Network Sharing](net-sharing.md)
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
# HTTP Data Request
## Use Cases
## When to Use
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
......@@ -14,40 +14,49 @@ For details about how to apply for permissions, see [Access Control Development]
The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md).
| API | Description |
| ----------------------------------------- | --------------------------------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| destroy() | Destroys an HTTP request. |
| API | Description |
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. |
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop
1. Import the required HTTP module.
2. Create an **HttpRequest** object.
3. (Optional) Listen for HTTP Response Header events.
4. Initiate an HTTP request to a given URL.
5. (Optional) Process the HTTP Response Header event and the return result of the HTTP request.
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements.
4. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned result based on service requirements.
6. Call **off()** to unsubscribe from HTTP response header events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
```js
// Import the http namespace.
import http from '@ohos.net.http';
// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused.
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add the header field based on service requirements.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
......@@ -55,21 +64,33 @@ httpRequest.request(
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // Optional. The default value is 60000, in ms.
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10.
}, (err, data) => {
if (!err) {
// data.result contains the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. Parse the content based on service requirements.
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to destroy the request if it is no longer needed.
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`HTTP`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
# Network Connection Management
## Introduction
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
- Consumer: a user of data networks, for example, an application or a system service.
- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- 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.
## When to Use
Typical application scenarios of network connection management are as follows:
- Subscribing to status changes of the specified network
- Obtaining the list of all registered networks
- Querying network connection information based on the data network
- Resolving the domain name of a network to obtain all IP addresses
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.|
| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.|
| ohos.net.connection.NetHandle | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetHandle | getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\<NetHandle>): void; |Subscribes to **netAvailable** events.|
| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.|
| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.|
| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.|
| ohos.net.connection.NetConnection | register(callback: AsyncCallback\<void>): void; |Registers an observer for the default network or the network specified in **createNetConnection**.|
| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\<void>): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.|
## Subscribing to Status Changes of the Specified Network
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
4. Call **conn.register()** to subscribe to network status changes of the specified network.
5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event.
6. Call **conn.unregister()** to unsubscribe from the network status changes if required.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
let netCap = {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
};
let netSpec = {
netCapabilities: netCap,
};
// Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpec, timeout);
// Listen to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', (data=> {
console.log("net is available, netId is " + data.netId);
}));
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data=> {
console.log("net is unavailable, netId is " + data.netId);
}));
// Register an observer for network status changes.
conn.register((err, data) => {});
// Unregister the observer for network status changes.
conn.unregister((err, data) => {});
```
## Obtaining the List of All Registered Networks
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAllNets** to obtain the list of all connected networks.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Obtain the list of all connected networks.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
```
## Querying Network Capability Information and Connection Information of Specified Data Network
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**.
3. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities.
4. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Call getDefaultNet to obtain the default data network specified by **NetHandle**.
connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netHandle = data;
}
})
// Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes.
for (let item of data.bearerTypes) {
if (item == 0) {
// Cellular network
console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) {
// Wi-Fi network
console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) {
// Ethernet network
console.log(JSON.stringify("BEARER_ETHERNET"));
}
}
// Obtain the specific network capabilities via networkCap.
for (let item of data.networkCap) {
if (item == 0) {
// The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) {
// The network traffic is not metered.
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) {
// The network has the Internet access capability, which is set by the network provider.
console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) {
// The network does not use a Virtual Private Network (VPN).
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) {
// The Internet access capability of the network is successfully verified by the connection management module.
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
}
}
})
// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
connection.getAllNets((err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
this.netList = data;
}
})
for (let item of this.netList) {
// Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
// Obtain the connection information of the network specified by each netHandle on the network list cyclically.
connection.getConnectionProperties(item, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
}
```
## Resolving the domain name of a network to obtain all IP addresses
### How to Develop
1. Import the connection namespace from **@ohos.net.connection.d.ts**.
2. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses.
```js
// Import the connection namespace.
import connection from '@ohos.net.connection'
// Use the default network to resolve the host name to obtain the list of all IP addresses.
connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
})
```
# Ethernet Connection
## Introduction
The Ethernet Connection module allows a device to access the Internet through a network cable.
After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical application scenarios of Ethernet connection are as follows:
- Dynamically assigning a series of network attributes, such as the IP address, subnet mask, gateway, and DNS in DHCP mode to enable network access
- Configuring a series of network attributes, such as the IP address, subnet mask, gateway, and DNS, in static mode to enable network access.
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Ethernet Connection](../reference/apis/js-apis-net-ethernet.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.ethernet | function setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\<void>): void | Configures the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | Obtains the network attributes of the specified Ethernet network. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | Checks whether the specified network port is active. This API uses an asynchronous callback to return the result.|
| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | Obtains the list of all active network ports. This API uses an asynchronous callback to return the result.|
## Ethernet Connection – DHCP Mode
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port. By default, an unconfigured Ethernet network uses the DHCP mode, in which the Ethernet network obtains the automatically assigned network attributes.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
## Ethernet Connection – Static Mode
### How to Develop
1. Use a network cable to connect the device to a network port.
2. Import the **ethernet** namespace from **@ohos.net.ethernet**.
3. Call **getAllActiveIfaces** in user mode to obtain the list of all active network ports, for example, **eth0** and **eth1**.
4. Call **isIfaceActive** in user mode to check whether the **eth0** port is active.
5. Call **setIfaceConfig** in user mode to set the **eth0** port to the static mode, in which you need to manually assign the network attributes (including the IP address, subnet mask, gateway, and DNS).
6. Call **getIfaceConfig** in user mode to obtain the static network attributes of the **eth0** port.
```js
// Import the ethernet namespace from @ohos.net.ethernet.
import ethernet from '@ohos.net.ethernet'
// Call getAllActiveIfaces to obtain the list of all active network ports.
ethernet.getAllActiveIfaces((error, data) => {
if (error) {
console.log("getAllActiveIfaces callback error = " + error);
} else {
console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]);
}
}
});
// Call isIfaceActive to check whether the specified network port is active.
ethernet.isIfaceActive("eth0", (error, data) => {
if (error) {
console.log("isIfaceActive callback error = " + error);
} else {
console.log("isIfaceActive callback = " + data);
}
});
// Call setIfaceConfig to configure the network attributes of the specified Ethernet network.
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx",
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => {
if (error) {
console.log("setIfaceConfig callback error = " + error);
} else {
console.log("setIfaceConfig callback ok ");
}
});
// Call getIfaceConfig to obtain the network attributes of the specified Ethernet network.
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) {
console.log("getIfaceConfig callback error = " + error);
} else {
console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
```
......@@ -2,15 +2,19 @@
Network management functions include:
- [HTTP Data Request](http-request.md): Initiates a data request through HTTP.
- [WebSocket Connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket Connection](socket-connection.md): Transmits data through Socket.
- [HTTP data request](http-request.md): Initiates a data request through HTTP.
- [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket.
- [Socket connection](socket-connection.md): Transmits data through Socket.
- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed.
- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
## Constraints
To use the functions of the network management module, you must obtain the permissions listed in the following table.
| Permission | Description |
| Permission | Description |
| -------------------------------- | -------------------------------------- |
| ohos.permission.GET_NETWORK_INFO | Allows an application to obtain the network connection information. |
| ohos.permission.SET_NETWORK_INFO | Allows an application to modify the network connection state. |
......
# Network Sharing
## Introduction
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## When to Use
Typical network sharing scenarios are as follows:
- Enabling network sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.sharing | function isSharingSupported(callback: AsyncCallback\<boolean>): void; | Checks whether the system supports network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function isSharing(callback: AsyncCallback\<boolean>): void; | Checks whether network sharing is active. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Starts network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void; | Stops network sharing. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsRxBytes(callback: AsyncCallback\<number>): void; | Obtains the received data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTxBytes(callback: AsyncCallback\<number>): void; | Obtains the sent data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getStatsTotalBytes(callback: AsyncCallback\<number>): void; | Obtains the total data traffic during network sharing, in KB. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<string>>): void; | Obtains the names of network interface cards (NICs) in the specified network sharing state.. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceState>): void; | Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<string>>): void; | Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.|
| ohos.net.sharing | function on(type: 'sharingStateChange', callback: Callback\<boolean>): void; | Subscribes to network sharing state changes.|
| ohos.net.sharing | function off(type: 'sharingStateChange', callback?: Callback\<boolean>): void; | Unsubscribes from network sharing state changes.|
| ohos.net.sharing | unction on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Subscribes to network sharing state changes of the specified NIC.|
| ohos.net.sharing | function off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void; | Unsubscribes from network sharing state changes of the specified NIC.|
| ohos.net.sharing | function on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void; | Subscribes to upstream NIC changes.|
| ohos.net.sharing | function off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void; | Unsubscribes from upstream NIC changes.|
## Enabling Network Sharing
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **startSharing** to start network sharing of the specified type.
4. Return the callback for successfully starting network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Disabling network sharing
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Subscribe to network sharing state changes.
3. Call **stopSharing** to stop network sharing of the specified type.
4. Return the callback for successfully stopping network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
```
## Obtaining the data traffic of the shared network
### How to Develop
1. Import the **sharing** namespace from **@ohos.net.sharing**.
2. Call **startSharing** to start network sharing of the specified type.
3. Call **getStatsTotalBytes** to obtain the data traffic generated during data sharing.
4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
# Socket Connection
## Introduction
## Use Cases
The Socket Connection module allows an application to transmit data over a Socket connection through the TCP, UDP, or TLS protocol.
Your application can transmit data through Socket connections. Currently, the TCP and UDP protocols are supported.
## Basic Concepts
- Socket: An abstraction of endpoints for bidirectional communication between application processes running on different hosts in a network.
- TCP: Transmission Control Protocol, which is a byte stream–based transport layer communication protocol that is connection-oriented and reliable.
- UDP: User Datagram Protocol, which is a simple datagram-oriented transport layer communication protocol.
- TLS: Transport Layer Security, which is a protocol that ensures the data confidentiality and integrity between communication programs.
## When to Use
Applications transmit data over TCP, UDP, or TLS Socket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket connections
## Available APIs
The Socket connection function is mainly implemented by the Socket module. The following table describes the related APIs.
For the complete list of APIs and example code, see [Socket Connection](../reference/apis/js-apis-socket.md).
| API| Description |
Socket connection functions are mainly implemented by the **socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| constructUDPSocketInstance() | Creates a **UDPSocket** object. |
| constructTCPSocketInstance() | Creates a **TCPSocket** object. |
| bind() | Binds the IP address and port number. |
| constructUDPSocketInstance() | Creates a **UDPSocket** object.|
| constructTCPSocketInstance() | Creates a **TCPSocket** object.|
| bind() | Binds the IP address and port number.|
| send() | Sends data.|
| close() | Closes a Socket connection. |
| getState() | Obtains the Socket connection status. |
| connect() | Connects to the specified IP address and port. This function is supported only for TCP. |
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API. |
| on(type:&nbsp;'message') | Enables listening for **message** events of the Socket connection. |
| off(type:&nbsp;'message') | Disables listening for **message** events of the Socket connection. |
| on(type:&nbsp;'close') | Enables listening for **close** events of the Socket connection. |
| off(type:&nbsp;'close') | Disables listening for **close** events of the Socket connection. |
| on(type:&nbsp;'error') | Enables listening for **error** events of the Socket connection. |
| off(type:&nbsp;'error') | Disables listening for **error** events of the Socket connection. |
| on(type:&nbsp;'listening') | Enables listening for **listening** events of the UDPSocket connection. |
| off(type:&nbsp;'listening') | Disables listening for **listening** events of the UDPSocket connection. |
| on(type:&nbsp;'connect') | Enables listening for **connect** events of the TCPSocket connection. |
| off(type:&nbsp;'connect') | Disables listening for **connect** events of the TCPSocket connection. |
| close() | Closes a Socket connection.|
| getState() | Obtains the Socket connection status.|
| connect() | Connects to the specified IP address and port. This function is supported only for TCP.|
| getRemoteAddress() | Obtains the peer address of the Socket connection. This function is supported only for TCP. The **connect** API must have been called before you use this API.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the Socket connection.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
TLS Socket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
| constructTLSSocketInstance() | Creates a **TLSSocket** object.|
| bind() | Binds the IP address and port number.|
| close(type:&nbsp;'error') | Closes a Socket connection.|
| connect() | Sets up a connection to the specified IP address and port number.|
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLS Socket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
## How to Develop
## Transmitting Data over TCP/UDP Socket Connections
The implementation is similar for UDPSocket and TCPSocket. The following uses the TCPSocket as an example.
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
1. Import the required Socket module.
1. Import the required **socket** module.
2. Create a **TCPSocket** object.
3. (Optional) Enable listening for TCPSocket events.
3. (Optional) Subscribe to TCP Socket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
......@@ -48,15 +85,15 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use.
7. Enable the TCP Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Enable listening for TCPSocket events.
// Subscribe to TCP Socket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
......@@ -73,7 +110,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
......@@ -86,6 +123,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
......@@ -100,6 +138,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
......@@ -112,7 +151,8 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket events.
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
......@@ -122,3 +162,167 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close');
}, 30 * 1000);
```
## Implementing Encrypted Data Transmission over TLS Socket Connections
### How to Develop
TLS Socket connection process on the client:
1. Import the required **socket** module.
2. Bind the IP address and port number of the server.
3. For two-way authentication, upload the client CA certificate and digital certificate. For one-way authentication, upload the client CA certificate.
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLS Socket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
address: {
address: "192.168.xx.xxx",
port: xxxx, // Port
family: 1,
},
// Set the parameters used for authentication during communication.
secureOptions: {
key: "xxxx", // Key
cert: "xxxx", // Digital certificate
ca: ["xxxx"], // CA certificate
passwd: "xxxx", // Password for generating the key
protocols: [socket.Protocol.TLSv12], // Communication protocol
useRemoteCipherPrefer: true, // Whether to preferentially use the peer cipher suite
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
family: 1,
},
secureOptions: {
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
console.log("close success");
}
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
```
## Samples
The following samples are provided to help you better understand how to develop Socket connection features:
- [`Socket`: Socket Connection (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [UDP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [TCP Socket (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
......@@ -34,7 +34,7 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
### Data Provider Application Development (Only for System Applications)
### Data Provider Application Development (for System Applications Only)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
......
# Device
# Device Management
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Location
- [Location Service Development](location-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Sensor
- [Sensor Overview](sensor-overview.md)
- [Sensor Development](sensor-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Update Service
- [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md)
- USB Service
- [USB Service Overview](usb-overview.md)
- [USB Service Development](usb-guidelines.md)
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
\ No newline at end of file
- Stationary
- [Stationary Development](stationary-guidelines.md)
......@@ -15,11 +15,11 @@ import pointer from '@ohos.multimodalInput.pointer';
The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md).
| Instance | API | Description |
| ------- | ------------------------------------------------------------ | --------------------------------------------------------------- |
| pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. |
| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally. |
| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. |
| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally.|
| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\<void>): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
## Hiding the Mouse Pointer
......@@ -77,43 +77,48 @@ When designing a color picker, you can have the mouse pointer switched to the co
5. Set the mouse pointer to the default style.
```js
import pointer from '@ohos.multimodalInput.pointer';
import window from '@ohos.window';
// 1. Enable the color pickup function.
// 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 3. Set the mouse pointer to the color picker style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
window.getLastWindow(this.context, (error, windowClass) => {
if (error.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
return;
}
var windowId = windowClass.getWindowProperties().id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 3. Set the mouse pointer to the color picker style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
});
// 4. End color pickup.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 5. Set the mouse pointer to the default style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
window.getLastWindow(this.context, (error, windowClass) => {
if (error.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
return;
}
var windowId = windowClass.getWindowProperties().id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 5. Set the mouse pointer to the default style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(`message`)}`);
}
});
```
# Stationary Development
## When to Use
An application can call the **Stationary** module to obtain the device status, for example, whether the device is absolutely or relatively still.
For details about the APIs, see [Stationary](../reference/apis/js-apis-stationary.md).
## Device Status Type Parameters
| Name| Description|
| -------- | -------- |
| still | Absolutely still.|
| relativeStill | Relatively still.|
## Parameters for Subscribing to Device Status events
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Event indicating entering device status. |
| EXIT | 2 | Event indicating exiting device status.|
| ENTER_EXIT | 3 | Event indicating entering and exiting device status.|
## Returned Device Status Parameters
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| ENTER | 1 | Entering device status. |
| EXIT | 2 | Exiting device status.|
## Available APIs
| Module | Name | Description |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback&lt;ActivityResponse&gt;): void | Subscribes to the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | once(activity: ActivityType, callback: Callback&lt;ActivityResponse&gt;): void | Obtains the device status. This API uses an asynchronous callback to return the result.|
| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback&lt;ActivityResponse&gt;): void | Unsubscribes from the device status. |
## Constraints
The device must support the acceleration sensor.
## How to Develop
1. Subscribe to the event indicating entering the absolute still state, and the event is reported every 1 second.
```js
import stationary from '@ohos.stationary';
var reportLatencyNs = 1000000000;
try {
stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
2. Obtain the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.once('still', (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
3. Unsubscribe from the event indicating entering the absolute still state.
```js
import stationary from '@ohos.stationary';
try {
stationary.off('still', stationary.ActivityEvent.ENTER, (data) => {
console.log('data='+ JSON.stringify(data));
})
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
......@@ -16,6 +16,10 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
| ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.|
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration in the specified mode. This API uses a promise to return the result. |
| ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback&lt;void&gt;): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. |
| ohos.vibrator | stopVibration(): Promise&lt;void&gt; | Stops vibration in all modes. This API uses a promise to return the result. |
| ohos.vibrator | stopVibration(callback: AsyncCallback&lt;void&gt;): void | Stops vibration in all modes. This API uses an asynchronous callback to return the result. |
| ohos.vibrator | isSupportEffect(effectId: string): Promise&lt;boolean&gt; | Checks whether the passed effect ID is supported. This API uses a promise to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. |
| ohos.vibrator | isSupportEffect(effectId: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the passed effect ID is supported. This API uses an asynchronous callback to return the result. The value **true** means that the passed effect ID is supported, and **false** means the opposite. |
## How to Develop
......@@ -27,7 +31,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
```js
import vibrator from '@ohos.vibrator';
try {
vibrator.startVibration({
vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
type: 'time',
duration: 1000,
}, {
......@@ -50,7 +54,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
```js
import vibrator from '@ohos.vibrator';
try {
// Stop vibration in VIBRATOR_STOP_MODE_TIME mode.
// Stop vibration in VIBRATOR_STOP_MODE_TIME mode. To use stopVibration, you must configure the ohos.permission.VIBRATE permission.
vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) {
if (error) {
console.log('error.code' + error.code + 'error.message' + error.message);
......@@ -62,3 +66,72 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
console.info('errCode: ' + err.code + ' ,msg: ' + err.message);
}
```
4. Stop vibration in all modes.
```js
import vibrator from '@ohos.vibrator';
// To use startVibration and stopVibration, you must configure the ohos.permission.VIBRATE permission.
try {
vibrator.startVibration({
type: 'time',
duration: 1000,
}, {
id: 0,
usage: 'alarm'
}, (error) => {
if (error) {
console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message);
return;
}
console.log('Callback returned to indicate a successful vibration.');
});
// Stop vibration in all modes.
vibrator.stopVibration(function (error) {
if (error) {
console.log('error.code' + error.code + 'error.message' + error.message);
return;
}
console.log('Callback returned to indicate successful.');
})
} catch (error) {
console.info('errCode: ' + error.code + ' ,msg: ' + error.message);
}
```
5. Check whether the passed effect ID is supported.
```js
import vibrator from '@ohos.vibrator';
try {
// Check whether 'haptic.clock.timer' is supported.
vibrator.isSupportEffect('haptic.clock.timer', function (err, state) {
if (err) {
console.error('isSupportEffect failed, error:' + JSON.stringify(err));
return;
}
console.log('The effectId is ' + (state ? 'supported' : 'unsupported'));
if (state) {
try {
vibrator.startVibration({ // To use startVibration, you must configure the ohos.permission.VIBRATE permission.
type: 'preset',
effectId: 'haptic.clock.timer',
count: 1,
}, {
usage: 'unknown'
}, (error) => {
if(error) {
console.error('haptic.clock.timer vibrator error:' + JSON.stringify(error));
} else {
console.log('haptic.clock.timer vibrator success');
}
});
} catch (error) {
console.error('Exception in, error:' + JSON.stringify(error));
}
}
})
} catch (error) {
console.error('Exception in, error:' + JSON.stringify(error));
}
```
# DFX
- Application Event Logging
- [Development of Application Event Logging](hiappevent-guidelines.md)
- Distributed Call Chain Tracing
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- HiLog
- [HiLog Development](hilog-guidelines.md)
- Performance Tracing
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md)
- Error Management
- [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
\ No newline at end of file
......@@ -12,11 +12,11 @@ Application error management APIs are provided by the **errorManager** module. F
| API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
| on(type: "error", observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| off(type: "error", observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| off(type: "error", observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer).
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result codes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API
......@@ -45,7 +45,8 @@ let callback = {
console.log(errMsg);
}
}
export default class EntryAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.on("error", callback);
......
......@@ -136,7 +136,7 @@ async function copySandbox2Public() {
console.error('file asset get failed, message = ' + err);
}
let fdPub = await fileAsset.open('rw');
let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE);
await fs.copyFile(fdSand.fd, fdPub);
await fileAsset.close(fdPub);
await fs.close(fdSand.fd);
......@@ -174,7 +174,7 @@ async function example() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then((asset) => {
media.createAsset(mediaType, "testFile.txt", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch((err) => {
console.error("createAsset failed with error: " + err);
......
......@@ -42,14 +42,11 @@ async function example() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.log('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
......@@ -75,14 +72,11 @@ async function example() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
......@@ -108,14 +102,11 @@ async function example() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject().then((fileAsset) => {
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}).catch((err) => {
console.error('Failed to get next object: ' + err);
});
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
......
......@@ -6,7 +6,7 @@ The [intl](intl-guidelines.md) module provides basic i18n capabilities through t
## Obtaining and Setting i18n Information
The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch.
The following table lists the APIs used to configure information such as the system language, preferred language, country or region, 24-hour clock, and use of local digits.
### Available APIs
......@@ -30,15 +30,15 @@ The system provides APIs to configure information such as the system language, p
| System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. |
| System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. |
| System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Sets whether to enable the local digit switch. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether the local digit switch is turned on. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Specifies whether to enable use of local digits. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether use of local digits is enabled. |
| | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.|
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Obtain and set the system language.
......@@ -51,7 +51,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLanguage("en"); // Set the system language to en.
let language = I18n.System.getSystemLanguage(); // language = "en"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -65,7 +65,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemRegion("CN"); // Set the system country to CN.
let region = I18n.System.getSystemRegion(); // region = "CN"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -79,7 +79,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN.
let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -92,7 +92,7 @@ The system provides APIs to configure information such as the system language, p
let rtl = I18n.isRTL("zh-CN"); // rtl = false
rtl = I18n.isRTL("ar"); // rtl = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -106,7 +106,7 @@ The system provides APIs to configure information such as the system language, p
I18n.System.set24HourClock(true);
let hourClock = I18n.System.is24HourClock(); // hourClock = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -121,7 +121,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false;
let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English"
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -136,7 +136,7 @@ The system provides APIs to configure information such as the system language, p
let sentenceCase = false;
let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S."
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -150,7 +150,7 @@ The system provides APIs to configure information such as the system language, p
let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"]
let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -162,7 +162,7 @@ The system provides APIs to configure information such as the system language, p
try {
let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -182,7 +182,7 @@ The system provides APIs to configure information such as the system language, p
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB"
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources.
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -190,14 +190,14 @@ The system provides APIs to configure information such as the system language, p
Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.)
Call **getUsingLocalDigit** to check whether the local digit switch is enabled.
Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur".
Currently, use of local digits is supported only for the following languages: **ar**, **as**, **bn**, **fa**, **mr**, **my**, **ne**, **ur**.
```js
try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
let status = I18n.System.getUsingLocalDigit(); // status = true
} catch(error) {
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`)
console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`);
}
```
......@@ -220,14 +220,14 @@ try {
| Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. |
| Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. |
| Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether the specified date in this **Calendar** object is a weekend. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether a given date is a weekend in the calendar. |
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **Calendar** object.
......@@ -254,7 +254,7 @@ try {
Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object.
```js
calendar.set(2021, 12, 21, 6, 0, 0)
calendar.set(2021, 12, 21, 6, 0, 0);
```
5. Set and obtain the time zone for the **Calendar** object.
......@@ -317,7 +317,7 @@ try {
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **PhoneNumberFormat** object.
......@@ -359,7 +359,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Convert a measurement unit.
......@@ -393,7 +393,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiates an **IndexUtil** object.
......@@ -418,7 +418,7 @@ The **I18NUtil** class provides an API to implement measurement conversion.
Call **addLocale** to add the alphabet index of a new locale to the current index list.
```js
indexUtil.addLocale("ar")
indexUtil.addLocale("ar");
```
5. Obtain the index of a string.
......@@ -454,7 +454,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate a **BreakIterator** object.
......@@ -462,7 +462,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
Call **getLineInstance** to instantiate a **BreakIterator** object.
```js
let locale = "en-US"
let locale = "en-US";
let breakIterator = I18n.getLineInstance(locale);
```
......@@ -531,7 +531,7 @@ When a text is displayed in more than one line, use [BreakIterator8](../referenc
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Instantiate the **TimeZone** object, and obtain the time zone information.
......@@ -592,7 +592,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Obtains the transliterator ID list.
......@@ -637,7 +637,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Check the input character has a certain attribute.
......@@ -719,7 +719,7 @@ Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
import I18n from '@ohos.i18n';
```
2. Check the sequence of year, month, and day in a date.
......
......@@ -25,7 +25,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiates a **Locale** object.
......@@ -100,7 +100,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **DateTimeFormat** object.
......@@ -170,7 +170,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **NumberFormat** object.
......@@ -195,7 +195,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug
```js
let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new Intl.NumberFormat("zh-CN", options);
let number = 1234.5678
let number = 1234.5678;
let formatResult = numberFormat.format(number); // formatResult = "1235"
```
......@@ -229,7 +229,7 @@ Users in different regions have different requirements for string sorting. [Coll
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **Collator** object.
......@@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll
let collator = new Intl.Collator();
```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8).
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9).
The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'.
```js
......@@ -290,7 +290,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **PluralRules** object.
......@@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let pluralRules = new Intl.PluralRules();
```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8).
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9).
```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
......@@ -313,7 +313,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
let number = 1234.5678
let number = 1234.5678;
let categoryResult = pluralRules.select(number); // categoryResult = "other"
```
......@@ -338,7 +338,7 @@ According to grammars in certain languages, the singular or plural form of a nou
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
import Intl from '@ohos.intl';
```
2. Instantiate a **RelativeTimeFormat** object.
......@@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let relativeTimeFormat = new Intl.RelativeTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8).
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9).
```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
......@@ -362,7 +362,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2;
let unit = "year"
let unit = "year";
let formatResult = relativeTimeFormat.format(number, unit); // 2 years later
```
......@@ -373,7 +373,7 @@ According to grammars in certain languages, the singular or plural form of a nou
```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2;
let unit = "year"
let unit = "year";
let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}]
```
......@@ -390,6 +390,4 @@ According to grammars in certain languages, the singular or plural form of a nou
The following sample is provided to help you better understand how to develop internationalization capabilities:
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International)
-[`International`: Internationalization (ArkTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
-[`International`: Internationalization (ArkTS) (API9) (Full SDK)] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International)
......@@ -12,10 +12,10 @@
- [Audio Routing and Device Management Development](audio-routing-manager.md)
- [AVPlayer Development (Recommended)](avplayer-playback.md)
- [AVRecorder Development (Recommended)](avrecorder.md)
- [Audio Playback Development](audio-playback.md)
- [Audio Recording Development](audio-recorder.md)
- [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md)
- [Audio Playback Development (To Be Deprecated Soon)](audio-playback.md)
- [Audio Recording Development (To Be Deprecated Soon)](audio-recorder.md)
- [Video Playback Development (To Be Deprecated Soon)](video-playback.md)
- [Video Recording Development (To Be Deprecated Soon)](video-recorder.md)
- AVSession
- [AVSession Overview](avsession-overview.md)
......
......@@ -27,32 +27,43 @@ Before developing the audio data collection feature, configure the **ohos.permis
For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8).
1. Use **createAudioCapturer()** to create an **AudioCapturer** instance.
1. Use **createAudioCapturer()** to create a global **AudioCapturer** instance.
Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification.
```js
import audio from '@ohos.multimedia.audio';
import audio from '@ohos.multimedia.audio';
import fs from '@ohos.file.fs'; // It will be used for the call of the read function in step 3.
// Perform a self-test on APIs related to audio rendering.
@Entry
@Component
struct AudioRenderer {
@State message: string = 'Hello World'
private audioCapturer: audio.AudioCapturer; // It will be called globally.
async initAudioCapturer(){
let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0.
}
let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
this.audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
console.log('AudioRecLog: Create audio capturer success.');
}
let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0.
}
let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
console.log('AudioRecLog: Create audio capturer success.');
```
2. Use **start()** to start audio recording.
......@@ -60,23 +71,18 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
```js
import audio from '@ohos.multimedia.audio';
async function startCapturer() {
let state = audioCapturer.state;
async startCapturer() {
let state = this.audioCapturer.state;
// The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) {
console.info('Capturer is not in a correct state to start');
return;
}
await audioCapturer.start();
state = audioCapturer.state;
if (state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
console.error('AudioRecLog: Capturer start failed');
if (state == audio.AudioState.STATE_PREPARED || state == audio.AudioState.STATE_PAUSED ||
state == audio.AudioState.STATE_STOPPED) {
await this.audioCapturer.start();
state = this.audioCapturer.state;
if (state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
console.error('AudioRecLog: Capturer start failed');
}
}
}
```
......@@ -86,91 +92,88 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The following example shows how to write recorded data into a file.
```js
import fs from '@ohos.file.fs';
let state = audioCapturer.state;
// The read operation can be performed only when the state is STATE_RUNNING.
if (state != audio.AudioState.STATE_RUNNING) {
console.info('Capturer is not in a correct state to read');
return;
}
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let file = fs.openSync(filePath, 0o2);
let fd = file.fd;
if (file !== null) {
console.info('AudioRecLog: file created');
} else {
console.info('AudioRecLog: file create : FAILED');
return;
}
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) {
let bufferSize = await audioCapturer.getBufferSize();
let buffer = await audioCapturer.read(bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
async readData(){
let state = this.audioCapturer.state;
// The read operation can be performed only when the state is STATE_RUNNING.
if (state != audio.AudioState.STATE_RUNNING) {
console.info('Capturer is not in a correct state to read');
return;
}
if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed');
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let file = fs.openSync(path, 0o2);
let fd = file.fd;
if (file !== null) {
console.info('AudioRecLog: file created');
} else {
let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`);
}
numBuffersToCapture--;
count++;
console.info('AudioRecLog: file create : FAILED');
return;
}
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
let numBuffersToCapture = 150; // Write data for 150 times.
let count = 0;
while (numBuffersToCapture) {
this.bufferSize = await this.audioCapturer.getBufferSize();
let buffer = await this.audioCapturer.read(this.bufferSize, true);
let options = {
offset: count * this.bufferSize,
length: this.bufferSize
}
if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed');
} else {
let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`);
}
numBuffersToCapture--;
count++;
}
}
```
4. Once the recording is complete, call **stop()** to stop the recording.
```js
async function StopCapturer() {
let state = audioCapturer.state;
// The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state.
if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) {
console.info('AudioRecLog: Capturer is not running or paused');
return;
}
await audioCapturer.stop();
state = audioCapturer.state;
if (state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer stopped');
} else {
console.error('AudioRecLog: Capturer stop failed');
}
}
async StopCapturer() {
let state = this.audioCapturer.state;
// The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state.
if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) {
console.info('AudioRecLog: Capturer is not running or paused');
return;
}
await this.audioCapturer.stop();
state = this.audioCapturer.state;
if (state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer stopped');
} else {
console.error('AudioRecLog: Capturer stop failed');
}
}
```
5. After the task is complete, call **release()** to release related resources.
```js
async function releaseCapturer() {
let state = audioCapturer.state;
// The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state.
if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) {
console.info('AudioRecLog: Capturer already released');
return;
}
await audioCapturer.release();
state = audioCapturer.state;
if (state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
} else {
console.info('AudioRecLog: Capturer release failed');
}
}
async releaseCapturer() {
let state = this.audioCapturer.state;
// The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state.
if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) {
console.info('AudioRecLog: Capturer already released');
return;
}
await this.audioCapturer.release();
state = this.audioCapturer.state;
if (state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
} else {
console.info('AudioRecLog: Capturer release failed');
}
}
```
6. (Optional) Obtain the audio capturer information.
......@@ -178,23 +181,20 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
You can use the following code to obtain the audio capturer information:
```js
// Obtain the audio capturer state.
let state = audioCapturer.state;
// Obtain the audio capturer information.
let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo();
// Obtain the audio stream information.
let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo();
// Obtain the audio stream ID.
let audioStreamId : number = await audioCapturer.getAudioStreamId();
// Obtain the Unix timestamp, in nanoseconds.
let audioTime : number = await audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size.
let bufferSize : number = await audioCapturer.getBufferSize();
async getAudioCapturerInfo(){
// Obtain the audio capturer state.
let state = this.audioCapturer.state;
// Obtain the audio capturer information.
let audioCapturerInfo : audio.AudioCapturerInfo = await this.audioCapturer.getCapturerInfo();
// Obtain the audio stream information.
let audioStreamInfo : audio.AudioStreamInfo = await this.audioCapturer.getStreamInfo();
// Obtain the audio stream ID.
let audioStreamId : number = await this.audioCapturer.getAudioStreamId();
// Obtain the Unix timestamp, in nanoseconds.
let audioTime : number = await this.audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size.
let bufferSize : number = await this.audioCapturer.getBufferSize();
}
```
7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
......@@ -202,12 +202,13 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
```js
audioCapturer.on('markReach', (reachNumber) => {
console.info('Mark reach event Received');
console.info(`The Capturer reached frame: ${reachNumber}`);
});
audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for.
async markReach(){
this.audioCapturer.on('markReach', 10, (reachNumber) => {
console.info('Mark reach event Received');
console.info(`The Capturer reached frame: ${reachNumber}`);
});
this.audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for.
}
```
8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event.
......@@ -215,40 +216,43 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
```js
audioCapturer.on('periodReach', (reachNumber) => {
console.info('Period reach event Received');
console.info(`In this period, the Capturer reached frame: ${reachNumber}`);
});
audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for.
async periodReach(){
this.audioCapturer.on('periodReach', 10, (reachNumber) => {
console.info('Period reach event Received');
console.info(`In this period, the Capturer reached frame: ${reachNumber}`);
});
this.audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for.
}
```
9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type.
```js
audioCapturer.on('stateChange', (state) => {
console.info(`AudioCapturerLog: Changed State to : ${state}`)
switch (state) {
case audio.AudioState.STATE_PREPARED:
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
console.info('Audio State is : Prepared');
break;
case audio.AudioState.STATE_RUNNING:
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
console.info('Audio State is : Running');
break;
case audio.AudioState.STATE_STOPPED:
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
console.info('Audio State is : stopped');
break;
case audio.AudioState.STATE_RELEASED:
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
console.info('Audio State is : released');
break;
default:
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
console.info('Audio State is : invalid');
break;
}
});
async stateChange(){
this.audioCapturer.on('stateChange', (state) => {
console.info(`AudioCapturerLog: Changed State to : ${state}`)
switch (state) {
case audio.AudioState.STATE_PREPARED:
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
console.info('Audio State is : Prepared');
break;
case audio.AudioState.STATE_RUNNING:
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
console.info('Audio State is : Running');
break;
case audio.AudioState.STATE_STOPPED:
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
console.info('Audio State is : stopped');
break;
case audio.AudioState.STATE_RELEASED:
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
console.info('Audio State is : released');
break;
default:
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
console.info('Audio State is : invalid');
break;
}
});
}
```
......@@ -292,13 +292,13 @@ export class AVPlayerDemo {
async avPlayerDemo() {
// Create an AVPlayer instance.
this.avPlayer = await media.createAVPlayer()
let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4'
let file = await fs.open(path)
fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath
let fileDescriptor = undefined
// Use getRawFileDescriptor of the resource management module to obtain the media assets in the application, and use the fdSrc attribute of the AVPlayer to initialize the media assets.
// For details on the fd/offset/length parameter, see the Media API. The globalThis.abilityContext parameter is a system environment variable and is saved as a global variable on the main page during the system boost.
await globalThis.abilityContext.resourceManager.getRawFileDescriptor('H264_AAC.mp4').then((value) => {
fileDescriptor = {fd: value.fd, offset: value.offset, length: value.length}
})
this.avPlayer.fdSrc = fileDescriptor
}
}
```
......
......@@ -53,10 +53,10 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
// Configure the parameters based on the audio file format.
SLDataFormat_PCM format_pcm = {
SL_DATAFORMAT_PCM,
OHOS::AudioStandard::AudioChannel::MONO,
OHOS::AudioStandard::AudioSamplingRate::SAMPLE_RATE_44100,
OHOS::AudioStandard::AudioSampleFormat::SAMPLE_S16LE,
SL_DATAFORMAT_PCM, // Input audio format.
1, // Mono channel.
SL_SAMPLINGRATE_44_1, // Sampling rate, 44100 Hz.
SL_PCMSAMPLEFORMAT_FIXED_16, // Audio sampling format, a signed 16-bit integer in little-endian format.
0,
0,
0
......
# Notification
- [Notification Overview](notification-overview.md)
- [Notification Subscription (Open Only to System Applications)](notification-subscription.md)
- [Notification Subscription (for System Applications)](notification-subscription.md)
- [Enabling Notification](notification-enable.md)
- Publishing a Notification
- [Publishing a Basic Notification](text-notification.md)
......
# Notification Subscription (Open Only to System Applications)
# Notification Subscription (for System Applications Only)
To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application.
......
......@@ -27,7 +27,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n
```ts
notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`);
let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite.
let isSupportTpl: boolean = data; // The value true means that the template of the downloadTemplate type is supported, and false means the opposite.
// ...
}).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`);
......
......@@ -127,10 +127,10 @@ The following table describes the APIs for notification publishing. You specify
Below is an example of the multi-line notification.
![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png)
- In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB.
- In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) object that does not exceed 2 MB.
```ts
let notificationPicture: PixelMap = undefined; // Obtain the pixel map information.
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
let notificationRequest: notificationManager.NotificationRequest = {
id: 1,
content: {
......@@ -141,7 +141,7 @@ The following table describes the APIs for notification publishing. You specify
additionalText: 'test_additionalText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
picture: notificationPicture
picture: imagePixelMap
}
}
}
......
# Quick Start
- Getting Started
- [Before You Start](start-overview.md)
- [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md)
......@@ -10,7 +11,6 @@
- Application Package Structure
- [Application Package Structure in Stage Model](application-package-structure-stage.md)
- [Application Package Structure in FA Model](application-package-structure-fa.md)
- [HAR File Structure](har-structure.md)
- Multi-HAP Mechanism
- [Multi-HAP Design Objectives](multi-hap-objective.md)
- [Multi-HAP Build View](multi-hap-build-view.md)
......@@ -18,6 +18,16 @@
- [Multi-HAP Usage Rules](multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md)
- [Application Installation and Uninstallation Process](application-package-install-uninstall.md)
- [Application Package Update Process](application-package-update.md)
- Shared Package
- [Shared Package Overview](shared-guide.md)
- [HAR](har-package.md)
- HSP
- [In-Application HSP Development](in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](cross-app-hsp.md)
- Quick Fix
- [Quick Fix Overview](quickfix-principles.md)
- [CLI-based Quick Fix Development](quickfix-debug.md)
- Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](app-configuration-file.md)
......
# Application Package Structure in Stage Model
To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged.
To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it will be helpful if you have a basic understanding of the structure of the application package created after the application is built and packaged, as well as the related basic concepts.
- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format.
- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file, and a module of the Library type is built into a [Harmony Archive (HAR)](har-package.md) file or a [Harmony Shared Package (HSP)](shared-guide.md).
A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below.
**Figure 1** Relationship between modules and UIAbility components
**Figure 1** Relationship between modules and UIAbility components
![ability-and-module](figures/ability-and-module.png)
Unless otherwise specified, the modules described in this document refer to the modules of the Ability type.
Unless otherwise specified, the modules described in this document refer to the modules of the Ability type.
- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature.
- HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature.
......@@ -27,6 +27,6 @@ To develop an application based on the [stage model](application-configuration-f
- The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md).
- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle.
**Figure 2** Application package structure in stage model
![app-pack-stage](figures/app-pack-stage.png)
\ No newline at end of file
**Figure 2** Application package structure in stage model
![app-pack-stage](figures/app-pack-stage.png)
# Application Package Update Process
The OpenHarmony bundle manager service allows application packages to be updated under the following scenarios:
1. In the application market: The application market notifies the user of an available update, and the user can install the update by following the onscreen instructions.
2. In the application: When the application for which an update is available starts up, the application market notifies the user of the update, and the user can install the update by following the onscreen instructions.
......@@ -42,6 +42,8 @@ ForEach(
)
```
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Description |
......
此差异已折叠。
# Full SDK Compilation Guide
The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can leverage this SDK to develop applications.
Since OpenHarmony 3.2 Beta5, the full SDK is not provided with the version. If necessary, you can compile the SDK using the full source code.
## Compiling the Full SDK
**Preparation**
1. Register an SSH public key for access to Gitee.
2. Configure the server environment. For details, see [Setting Up the Ubuntu Environment](../../device-dev/quick-start/quickstart-ide-env-ubuntu.md).
**Procedure**
1. Download and initialize the manifest repository: **repo init -u https://gitee.com/openharmony/manifest.git -b $manifest_branch --no-repo-verify --repo-url=https://gitee.com/oschina/repo --no-clone-bundle**
2. Download source code based on the downloaded manifest repository: **repo sync -c -d --force-sync**
3. Perform precompilation: **yes y | apt install libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev && rm -rf prebuilts/clang/ohos/darwin-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/windows-x86_64/clang-480513 && rm -rf prebuilts/clang/ohos/linux-x86_64/clang-480513 && bash build/prebuilts_download.sh -ndk && apt-get update -qqy && apt-get install doxygen -y --force-yes**
4. Perform compilation: **./build.sh --product-name ohos-sdk**
If the compilation is successful, export the files in the **out/sdk/packages/ohos-sdk/** directory.
## Replacing the SDK
After the full SDK is compiled, switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md).
此差异已折叠。
# HAR File Structure
The OpenHarmony Archive (HAR) file enables code to be shared among multiple modules or projects. Unlike a Harmony Ability Package (HAP) file, a HAR file cannot be independently installed on a device. Instead, it can only be referenced as the dependency of an application module.
A HAR file is the build product of a [module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) of the Library type in a DevEco Studio project.
As a static shared package in OpenHarmony, the [HAR file](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) can contain the source code, C++ libraries, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model).
此差异已折叠。
# CLI-based Quick Fix Development
You can use the command-line tool to develop a quick fix file, an expeditious approach to resolve application bugs. In this document, an application with the bundle name of **com.ohos.quickfix** in version 1000000 is used as an example to describe how to develop a quick fix file with the command-line tool.
## Writing the patch.json File
Write a **patch.json** file that meets your project requirements and place it in any directory of the project. (Configuring the **patch.json** file is not supported in DevEco Studio.) Create a **patch.json** file on the local computer. Below is an example of the file content:
```json
{
"app" : {
"bundleName" : "com.ohos.quickfix",
"versionCode": 1000000, // Application version
"versionName" : "1.0.0.1",
"patchVersionCode": 1000000, // Patch version
"patchVersionName" : "1.0.0.1"
},
"module" : {
"name" : "entry",
"type" : "patch",
"deviceTypes" : [
"default",
"tablet"
],
"originalModuleHash": "11223344556677889900" // SHA-256 value of the HAP file to restore
}
}
```
## Generating a Quick Fix File
### Quick Fix for TS Code
* After modifying the TS code file in DevEco Studio and build it into a HAP file, you can find the corresponding .abc file in the project directory, for example, **build\default\cache\default\LegacyCompileETS\jsbundle\temporary\pages\index.abc**.
### Quick Fix for C++ Code
* In DevEco Studio, build the original C++ code into a .so file. Fix bugs in the code and rebuild the code into a new .so file. You can find this .so file in the project directory, for example, **build\default\intermediates\libs\default\arm64-v8a\libentry.so**.
* Locate the **diff.exe** tool in the **toolchains** folder in the local OpenHarmony SDK path. Use this tool to generate a quick fix .so file based on the old and new .so files. The command is as follows:
```shell
$ diff.exe -s Example.z.so -d Example.z.so -p Example.z.so.diff
```
The command contains the following options:
- -**s**: path to the old .so file
- -**d**: path to the new .so file
- -**p**: path of the generated differential file
## Generating a Quick Fix File in .hqf Format
With the preceding **patch.json**, .abc, and .so files, run the following command to generate an .hqf file using the **app_packing_tool.jar** tool in the **toolchains** folder in the local OpenHarmony SDK path:
```shell
$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-patch patchs --out-path entry-default-unsigned.hqf --force true
```
The command contains the following options.
| Option|Description | Remarks|
| --- | --- |---|
| mode |Mode. | Mandatory|
| json-path|Path to the **patch.json** file.|Mandatory|
| lib-path|Path to the quick fix .so file. For details about the path, see [Structure of the Quick Fix Package](quickfix-principles.md#structure-of-the-quick-fix-package).|Optional|
| ets-path|Path to the quick fix .abc file.|Optional|
## Signing the Quick Fix File
Use the [hapsigner](../security/hapsigntool-guidelines.md) tool to sign the **entry-default-unsigned.hqf** file, in the same way you sign a HAP file. To be specific, run the following command to use **hap-sign-tool.jar** in the **toolchains** folder in the local OpenHarmony SDK path:
```shell
$ java -jar hap-sign-tool.jar sign-app -keyAlias "OpenHarmony Application Release" -signAlg "SHA256withECDSA" -mode "localSign" -appCertFile "OpenHarmonyApplication.pem" -profileFile "ohos_provision_release.p7b" -inFile "entry-default-unsigned.hqf" -keystoreFile "OpenHarmony.p12" -outFile "entry-signed-release.hqf" -keyPwd "123456" -keystorePwd "123456"
```
## Installing the Quick Fix File
Push the **entry-signed-release.hqf** file to the device.
```shell
hdc.exe file send .\entry-signed-release.hqf /data/
```
Run the following command to install the quick fix file as a patch:
```shell
$ bm quickfix -a -f /data/entry-signed-release.hqf
```
The complete commands are as follows:
```
$ bm quickfix -h
usage: bm quickfix <options>
options list:
-h, --help list available commands
-q, --query indicates query quickfix, used with -b or --bundle-name
-b, --bundle-name <bundle-name> query quickfix status and information by a specified bundle name
-a, --apply indicates apply quickfix, used with -f or --file-path
-f, --file-path <file-path> apply a quickfix file by a specified path
-f, --file-path <file-path> <file-path> ... apply some quickfix files of one bundle
-f, --file-path <bundle-direction> apply quickfix files by direction, under which are quickfix files
```
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册