提交 5d34ee2b 编写于 作者: H HelloCrease

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/HelloCrease/docs...

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/HelloCrease/docs into OpenHarmony-3.2-Release
......@@ -12,7 +12,7 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **myabilitystage**.
2. In the **myabilitystage** directory, right-click and choose **New > ts File** to create a file named **MyAbilityStage.ts**.
2. In the **myabilitystage** directory, right-click and choose **New > TypeScript File** to create a file named **MyAbilityStage.ts**.
3. Open the **MyAbilityStage.ts** file, and import the dependency package of AbilityStage. Customize a class that inherits from AbilityStage, and add the required lifecycle callbacks. The following code snippet adds the **onCreate()** lifecycle callback.
......@@ -20,16 +20,27 @@ AbilityStage is not automatically generated in the default project of DevEco Stu
import AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage {
onCreate() {
// When the HAP of the application is loaded for the first time, initialize the module.
}
onAcceptWant(want) {
// Triggered only for the ability with the specified launch type.
return "MyAbilityStage";
}
onCreate() {
// When the HAP of the application is loaded for the first time, initialize the module.
}
onAcceptWant(want) {
// Triggered only for the ability with the specified launch type.
return "MyAbilityStage";
}
}
```
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).
......@@ -49,9 +60,8 @@ When an application is switched to the background, it is cached in the backgroun
import AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
// Release unnecessary memory based on the change of available system memory.
}
onMemoryLevel(level) {
// Release unnecessary memory based on the change of available system memory.
}
}
```
......@@ -12,10 +12,13 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca
This document is organized as follows:
- [Creating an AccessibilityExtAbility File](#creating-an-accessibility-extension-service)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
- [AccessibilityExtensionAbility Development](#accessibilityextensionability-development)
- [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service)
- [Creating a Project](#creating-a-project)
- [Creating an AccessibilityExtAbility File](#creating-an-accessibilityextability-file)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
## Creating an Accessibility Extension Service
......@@ -79,13 +82,13 @@ You can also process physical key events in the accessibility extension service.
## Declaring Capabilities of Accessibility Extension Services
After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntrance** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail.
After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntry** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail.
```json
"extensionAbilities": [
{
"name": "AccessibilityExtAbility",
"srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts",
"srcEntry": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts",
"label": "$string:MainAbility_label",
"description": "$string:MainAbility_desc",
"type": "accessibility",
......
......@@ -187,13 +187,13 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../
> **NOTE**
>
> To obtain the context of another application:
>
>
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
>
> - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -248,7 +248,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../
In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to UIAbility lifecycle changes in a process.
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered. Each time the callback is registered, a listener lifecycle ID is returned, with the value incremented by 1 each time. When the number of listeners exceeds the upper limit (2^63-1), **-1** is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered. Each time the callback is registered, a listener lifecycle ID is returned, with the value incremented by 1 each time. When the number of listeners exceeds the upper limit (2^63-1), **-1** is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
```ts
......@@ -308,7 +308,7 @@ export default class EntryAbility extends UIAbility {
// Obtain the application context.
let applicationContext = this.context.getApplicationContext();
// Register the application lifecycle callback.
this.lifecycleId = applicationContext.on('Lifecycle', abilityLifecycleCallback);
this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
console.log(TAG, `register callback number: ${this.lifecycleId}`);
}
......
......@@ -74,7 +74,7 @@ Multiple widgets of the same application can be configured to implement differen
}
Row() {// Content that is updated only in state A
Text('状态A: ')
Text('State A: ')
Text(this.textA)
}
......
......@@ -22,8 +22,6 @@ A static subscriber is started once it receives a target event published by the
You can implement service logic in the **onReceiveEvent** callback.
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:
......@@ -35,12 +33,12 @@ A static subscriber is started once it receives a target event published by the
"extensionAbilities": [
{
"name": "StaticSubscriber",
"srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts",
"srcEntry": "./ets/StaticSubscriber/StaticSubscriber.ts",
"description": "$string:StaticSubscriber_desc",
"icon": "$media:icon",
"label": "$string:StaticSubscriber_label",
"type": "staticSubscriber",
"visible": true,
"exported": true,
"metadata": [
{
"name": "ohos.extension.staticSubscriber",
......@@ -56,7 +54,7 @@ A static subscriber is started once it receives a target event published by the
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.
- **srcEntry**: 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**.
......@@ -98,5 +96,5 @@ A static subscriber is started once it receives a target event published by the
"ohos.extension.staticSubscriber",
"xxx"
}
```
```
# 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).
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 [Cross-Application Data Sharing Overview](../database/share-device-data-across-apps-overview.md).
......@@ -2,12 +2,11 @@
## Introduction to EnterpriseAdminExtensionAbility
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 when a device administrator application is enabled or disabled or an application is installed or uninstalled.
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
EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
EnterpriseAdminExtensionAbility is applicable only to enterprise administrator applications.
## Observing Activation/Deactivation of a Device Administrator Application and Installation/Removal of an Application
......@@ -24,59 +23,59 @@ EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Manag
### Available APIs
| Class | API | Description |
| :------------------------------ | ----------------------------------------- | ---------------------------- |
| ------------------------------ | ----------------------------------------- | ---------------------------- |
| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when a device administrator application is activated. |
| 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, 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 **Module** project, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
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. 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");
}
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 corresponding to the project module. Set **type** to **enterpriseAdmin** and **srcEntrance** to the path of the ExtensionAbility code.
```ts
"extensionAbilities": [
{
"name": "ohos.samples.enterprise_admin_ext_ability",
"type": "enterpriseAdmin",
"visible": true,
"srcEntrance": "./ets/enterpriseextability/EnterpriseAdminAbility.ts"
}
]
```
```ts
import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
console.info("onAdminEnabled");
}
onAdminDisabled() {
console.info("onAdminDisabled");
}
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 corresponding to the project module. Set **type** to **enterpriseAdmin** and **srcEntry** to the path of the ExtensionAbility code.
```ts
"extensionAbilities": [
{
"name": "ohos.samples.enterprise_admin_ext_ability",
"type": "enterpriseAdmin",
"exported": true,
"srcEntry": "./ets/enterpriseextability/EnterpriseAdminAbility.ts"
}
]
```
## Example
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.
Use **subscribeManagedEvent** 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. To unsubscribe from events, use **unsubscribeManagedEvent**.
```ts
@State managedEvents: Array<adminManager.ManagedEvent> = [0,1]
......@@ -105,3 +104,4 @@ Use **subscribeManagedEvent()** and **unsubscribeManagedEvent()** in the @ohos.e
})
}
```
......@@ -187,7 +187,7 @@ On device A, touch the **Start** button provided by the initiator application to
// ...
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the target UIAbility.
......@@ -384,12 +384,12 @@ The following describes how to implement multi-device collaboration through cros
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"srcEnty": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
"exported": true
}]
```
......@@ -459,7 +459,7 @@ The following describes how to implement multi-device collaboration through cros
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD)
this.callee.off(MSG_SEND_METHOD)
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`)
}
......@@ -491,7 +491,7 @@ The following describes how to implement multi-device collaboration through cros
if (data != null) {
caller = data
console.info('get remote caller success')
// Register the onRelease listener of the CallerAbility.
// Register the onRelease() listener of the CallerAbility.
caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`)
})
......
......@@ -54,7 +54,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
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.
In the **InputMethodService.ts** 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';
......@@ -233,7 +233,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file.
```ets
```ts
import { numberSourceListData, sourceListType } from './keyboardKeyData'
@Component
......@@ -342,7 +342,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
}
```
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.
Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntry** to the code path of the InputMethodExtensionAbility component.
```ts
{
......@@ -353,9 +353,9 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
"description": "inputMethod",
"icon": "$media:icon",
"name": "InputMethodExtAbility",
"srcEntrance": "./ets/inputmethodextability/InputMethodService.ts",
"srcEntry": "./ets/inputmethodextability/InputMethodService.ts",
"type": "inputMethod",
"visible": true,
"exported": true,
}
]
}
......
# LifecycleApp Switching
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model|
| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model|
| -------- | -------- | -------- |
| onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).|
| onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback&lt;WindowStageEventType&gt;): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)<br>Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).|
| onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) |
| onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) |
| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) |
| onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.|
| onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.|
| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) |
| onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In standard or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.|
| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)<br>In multiton or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.|
| onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) |
| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) |
| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)<br>After the application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.|
......
......@@ -8,16 +8,19 @@ The following describes how the mission list manager manages the UIAbility insta
- **singleton**: Only one UIAbility instance exists for an application.
**Figure 1** Missions and singleton mode
![mission-and-singleton](figures/mission-and-singleton.png)
- **standard**: Each time **startAbility()** is called, a UIAbility instance is created in the application process.
- **multiton**: Each time **startAbility()** is called, a **UIAbility** instance is created in the application process.
**Figure 2** Missions and multiton mode
**Figure 2** Missions and standard mode
![mission-and-standard](figures/mission-and-standard.png)
![mission-and-multiton](figures/mission-and-standard.png)
- **specified**: The ([onAcceptWant](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create an instance.
- **specified**: The ([onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create an instance.
**Figure 3** Missions and specified mode
![mission-and-specified](figures/mission-and-specified.png)
......
......@@ -13,6 +13,7 @@ Before getting started with the development of mission management, be familiar w
- MissionListManager: system mission management module that maintains all the MissionLists and is consistent with the list in **Recents**.
**Figure 1** Mission management
![mission-list-manager](figures/mission-list-manager.png)
......
......@@ -8,7 +8,7 @@ When switching an application from the FA model to the stage model, you must mig
| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference|
| -------- | -------- | -------- | -------- |
| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| mainElement | The field name is changed, and the stage mode does not use the period (.) in ability names.|
| package | Package name of the HAP file, which must be unique in the application.| / | The stage model uses **name** to ensure application uniqueness. To ensure a successful switching from the FA model to the stage model, **name** in the stage model must be the same as **package** in the FA model.|
| package | Package name of the HAP file, which must be unique in the application.| / | The stage model uses **name** to ensure application uniqueness. |
| name | Class name of the HAP file.| / | This configuration is not enabled in the FA model, and the stage model does not have such a field.|
| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined.| / | This configuration is deprecated in the stage model.|
| moduleName in the distro object| Name of the current HAP file.<br>moduleName in the distro object.| name | The field name is changed.|
......@@ -21,11 +21,12 @@ When switching an application from the FA model to the stage model, you must mig
| shortcuts | Shortcuts of the application.| shortcut_config.json| In the stage model, the **shortcut_config.json** file is defined in **resources/base/profile** in the development view.|
| reqPermissions | Permissions that the application requests from the system when it is running.| requestPermissions | The field name is changed.|
| colorMode | Color mode of the application.| / | This configuration is not supported in the stage model.|
| distroFilter | Distribution rules of the application.| distroFilter_config.json| In the stage model, the **distroFilter_config.json** file is defined in **resources/base/profile** in the development view.|
| distributionFilter | Distribution rules of the application.| distroFilter_config.json| In the stage model, the **distroFilter_config.json** file is defined in **resources/base/profile** in the development view.|
| reqCapabilities | Device capabilities required for running the application.| / | This configuration is not supported in the stage model.|
| commonEvents | Common events.| common_event_config.json| In the stage model, the **common_event_config.json** file is defined in **resources/base/profile** in the development view.|
| entryTheme | Keyword of an OpenHarmony internal theme.| / | This configuration is not supported in the stage model.|
### Table 2 metaData Comparison
| Field Name Under metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference|
......@@ -40,7 +41,8 @@ When switching an application from the FA model to the stage model, you must mig
| -------- | -------- | -------- | -------- |
| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| name | None.|
| value | Value of the data item. The value is a string with a maximum of 255 bytes.| value | None.|
| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table-4-metadata-examples).|
| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table 4-metadata-examples).|
### Table 4 metaData Examples
......@@ -69,5 +71,5 @@ When switching an application from the FA model to the stage model, you must mig
| formsEnabled | Whether the ability can provide widgets.| / | This configuration is not supported in the stage model.|
| forms | Information about the widgets used by the ability. This field is valid only when **formsEnabled** is set to **true**.| form_config.json| In the stage model, the **form_config.json** file is defined in **resources/base/profile** in the development view.|
| srcLanguage | Programming language used to develop the ability.| / | This configuration is not supported in the stage model.|
| srcPath | Path of the JS component code corresponding to the ability.| srcEntrance | Path of the JS code corresponding to the ability.|
| srcPath | Path of the JS component code corresponding to the ability.| srcEnty | Path of the JS code corresponding to the ability.|
| uriPermission | Application data that the ability can access.| / | This configuration is not supported in the stage model.|
......@@ -5,10 +5,10 @@ Depending on the launch type, the action performed when the PageAbility starts d
**Table 1** PageAbility launch types
| Launch Type| Description|
| -------- | -------- |
| singleton | Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.<br>A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.|
| standard | Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.<br>A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.|
| Launch Type| Meaning | Description|
| -------- | -------- | -------- |
| singleton | Singleton mode| Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.<br>A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.|
| standard | Multiton mode| Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.<br>A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.|
You can set **launchType** in the **config.json** file to configure the launch type. The sample code is as follows:
......@@ -19,8 +19,8 @@ You can set **launchType** in the **config.json** file to configure the launch t
// ...
"abilities": [
{
// singleton mode.
// standard mode.
// singleton means the singleton mode.
// standard means the multiton mode.
"launchType": "standard",
// ...
}
......@@ -30,7 +30,8 @@ You can set **launchType** in the **config.json** file to configure the launch t
```
When the PageAbility is started for the first time (either in standard or singleton mode), the [PageAbility lifecycle callbacks](pageability-lifecycle.md#table13118194914476) are triggered. When it is not started for the first time in singleton mode, the **onNewWant()** callback (as described in the table below) is triggered, but the **onCreate()** callback is not.
When the PageAbility is started in multiton mode or it is started in singleton mode for the first time, the [PageAbility lifecycle callbacks](pageability-lifecycle.md#table13118194914476) are triggered. When it is not started for the first time in singleton mode, the **onNewWant()** callback (as described in the table below) is triggered, but the **onCreate()** callback is not.
**Table 2** Callbacks specific to the singleton mode
......
......@@ -15,7 +15,8 @@ The OpenHarmony process model is shown below.
> NOTE
>
> You can create ServiceExtensionAbility and DataShareExtensionAbility only for system applications.
> - You can create ServiceExtensionAbility and DataShareExtensionAbility only for system applications.
> - To view information about all running processes, run the **hdc shell** command to enter the shell CLI of the device, and run the **ps -ef** command.
A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names.
......
......@@ -7,13 +7,14 @@ Generally, UI redirection within an application is triggered by users. However,
The PageAbility has a UI. It can use **startAbility()** to start an ability that has a UI and is visible to users.
The **visible** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components.
The **exported** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components.
**Table 1** Description of visible
**Table 1** Description of exported
| Name| Description| Initial Value Allowed|
| -------- | -------- | -------- |
| visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by any application.<br>**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)|
| exported | Whether the ability can be called by other applications.<br>**true**: The ability can be called by any application.<br>**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)|
To enable an ability to be called by any application, configure the **config.json** file as follows:
......@@ -24,7 +25,7 @@ To enable an ability to be called by any application, configure the **config.jso
// ...
"abilities": [
{
"visible": "true",
"exported": "true",
// ...
}
]
......@@ -33,4 +34,4 @@ To enable an ability to be called by any application, configure the **config.jso
```
If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant.
If the ability contains **skills**, you are advised to set **exported** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **exported** set to **false** are home screen, voice assistant, or search assistant.
......@@ -12,7 +12,7 @@ import featureAbility from '@ohos.ability.featureAbility';
async function restartAbility() {
let wantInfo = {
bundleName: "com.sample.MyApplication",
abilityName: "EntryAbility",
abilityName: "MainAbility",
parameters: {
page: "pages/second"
}
......@@ -70,7 +70,7 @@ struct Index {
```
When the launch type of a PageAbility is set to **standard** or when the PageAbility with the launch type set to **singleton** is started for the first time, you can use the **parameters** parameter in **want** to transfer the pages information and use the **startAbility()** method to start the PageAbility. For details about the launch type, see [PageAbility Launch Type](pageability-launch-type.md). The target PageAbility can use the **featureAbility.getWant()** method in **onCreate** to obtain the **want** parameter, and then call **router.push** to start a specified page.
When a PageAbility in multiton mode is started or when the PageAbility in singleton mode is started for the first time, you can use the **parameters** parameter in **want** to transfer the pages information and use the **startAbility()** method to start the PageAbility. For details about the launch type, see [PageAbility Launch Type](pageability-launch-type.md). The target PageAbility can use the **featureAbility.getWant()** method in **onCreate** to obtain the **want** parameter, and then call **router.push** to start a specified page.
When a user touches the button on the page of the caller PageAbility, the **startAbility()** method is called to start the target PageAbility. The **want** parameter in **startAbility()** carries the specified page information.
......@@ -89,7 +89,7 @@ struct Index {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
abilityName: "com.exm.myapplication.MainAbility",
parameters: { page: "pages/page1" }
}
}).then((data) => {
......@@ -104,7 +104,7 @@ struct Index {
featureAbility.startAbility({
want: {
bundleName: "com.exm.myapplication",
abilityName: "com.exm.myapplication.EntryAbility",
abilityName: "com.exm.myapplication.MainAbility",
parameters: { page: "pages/page2" }
}
}).then((data) => {
......
......@@ -2,19 +2,14 @@
For an OpenHarmony application, each process has a main thread to provide the following functionalities:
- Manage other threads.
- Enable multiple UIAbility components of the same application to share the same main thread.
- Distribute input events.
- Draw the UI.
- Invoke application code callbacks (event processing and lifecycle callbacks).
- Manage the ArkTS engine instance of the main thread so that multiple UIAbility components can run on it.
- Manage ArkTS engine instances of other threads (such as the worker thread), for example, starting and terminating other threads.
- Distribute interaction events.
- Process application code callbacks (event processing and lifecycle management).
- Receive messages sent by the worker thread.
In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. It cannot directly operate the UI. The worker thread is created in the main thread and is independent of the main thread. A maximum of seven worker threads can be created.
In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. The worker thread is created in the main thread and is independent from the main thread. It cannot directly operate the UI. A maximum of seven worker threads can be created.
![thread-model-stage](figures/thread-model-stage.png)
......@@ -22,4 +17,5 @@ Based on the OpenHarmony thread model, different services run on different threa
> **NOTE**
>
> The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread.
> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread.
> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p *<pid>* -T command**, where *<pid>* indicates the ID of the application process.
......@@ -38,7 +38,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
info: 'From the Index page of EntryAbility',
},
}
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => {
// ...
}).catch((err) => {
......@@ -65,7 +65,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility.
```ts
// context is the UIAbilityContext of the UIAbility instance to stop.
// context is the AbilityContext of the UIAbility instance to stop.
this.context.terminateSelf((err) => {
// ...
});
......@@ -88,7 +88,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
info: 'From the Index page of EntryAbility',
},
}
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => {
// ...
}).catch((err) => {
......@@ -124,7 +124,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
// ...
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the target UIAbility.
......@@ -187,7 +187,7 @@ This section describes how to start the UIAbility of another application through
entities: ['entity.system.default'],
}
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => {
// ...
}).catch((err) => {
......@@ -251,7 +251,7 @@ If you want to obtain the return result when using implicit Want to start the UI
entities: ['entity.system.default'],
}
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => {
// ...
}).catch((err) => {
......@@ -289,7 +289,7 @@ If you want to obtain the return result when using implicit Want to start the UI
// Want parameter information.
};
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the target UIAbility.
......@@ -322,7 +322,7 @@ let wantInfo = {
router: 'funcA',
},
}
// context is the UIAbilityContext of the initiator UIAbility.
// context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => {
// ...
}).catch((err) => {
......@@ -500,12 +500,12 @@ For the CalleeAbility, implement the callback to receive data and the methods to
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"srcEnty": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
"exported": true
}]
```
......@@ -596,7 +596,7 @@ For the CalleeAbility, implement the callback to receive data and the methods to
2. Obtain the caller interface.
The **UIAbilityContext** attribute implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **UIAbilityContext**, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements.
The **context** attribute of the UIAbility implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the UIAbility, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements.
```ts
......
......@@ -6,7 +6,7 @@ The launch type of the UIAbility component refers to the state of the UIAbility
- [Singleton](#singleton)
- [Standard](#standard)
- [Multiton](#multiton)
- [Specified](#specified)
......@@ -18,8 +18,7 @@ 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
![uiability-launch-type1](figures/uiability-launch-type1.png)
![uiability-launch-type1](figures/uiability-launch-type1.gif)
> **NOTE**
>
......@@ -43,15 +42,15 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration
```
## Standard
## Multiton
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**.
In multiton 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
**Figure 2** Demonstration effect in multiton mode
![standard-mode](figures/standard-mode.png)
![uiability-launch-type2](figures/uiability-launch-type2.gif)
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
To use the multiton mode, set **launchType** in the [module.json5 file](../quick-start/module-configuration-file.md) to **multiton**.
```json
......@@ -60,7 +59,7 @@ To use the standard mode, set **launchType** in the [module.json5 configuration
// ...
"abilities": [
{
"launchType": "standard",
"launchType": "multiton",
// ...
}
]
......@@ -73,14 +72,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
![uiability-launch-type2](figures/uiability-launch-type2.png)
**Figure 3** Demonstration effect in specified mode
![uiability-launch-type3](figures/uiability-launch-type3.gif)
For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **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**.
```json
{
"module": {
......@@ -95,8 +93,8 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
}
```
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](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instance.
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.
......@@ -120,10 +118,11 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
// ...
})
```
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';
......@@ -140,12 +139,12 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
}
}
```
> **NOTE**
>
> 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 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.
......@@ -153,6 +152,4 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
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 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.
......@@ -37,7 +37,7 @@ To enable an application to properly use a UIAbility component, declare the UIAb
"abilities": [
{
"name": "EntryAbility", // Name of the UIAbility component.
"srcEntrance": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component.
"srcEnty": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component.
"description": "$string:EntryAbility_desc", // Description of the UIAbility component.
"icon": "$media:icon", // Icon of the UIAbility component.
"label": "$string:EntryAbility_label", // Label of the UIAbility component.
......
......@@ -364,7 +364,7 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi
> **NOTE**
>
> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
> In the FA model, only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
- HML: uses web-like paradigm components to describe the widget page information.
......@@ -452,7 +452,7 @@ You can set router and message events for components on a widget. The router eve
2. Set the router event.
- **action**: **"router"**, which indicates a router event.
- **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default MainAbility name created by DevEco Studio in the FA model is com.example.entry.MainAbility.
- **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.MainAbility.
- **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the MainAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
3. Set the message event.
......@@ -543,4 +543,3 @@ The following is an example:
}
}
```
......@@ -11,7 +11,7 @@ Widget switching involves the following parts:
| Configuration Item | FA Model | Stage Model |
| ---------------- | ------------------------------------------- | ------------------------------------------------------------ |
| Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.|
| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntrance**, with the file name. |
| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEnty**, with the file name. |
| Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. |
| Whether to enable widgets | formsEnabled | This configuration item is unavailable. The setting of **type** set to **form** means that the widgets are enabled. |
| Ability type | type: service | type: form |
......@@ -32,7 +32,7 @@ Figure 2 Widget configuration differences
| Item| FA Model| Stage Model|
| -------- | -------- | -------- |
| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEntrance**|
| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEnty**|
| Lifecycle| export default| import FormExtension from '\@ohos.app.form.FormExtensionAbility';<br>export default class FormAbility extends FormExtension|
......
# WindowExtensionAbility
[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application.
......@@ -14,7 +15,7 @@ the context is [WindowExtensionContext](../reference/apis/js-apis-inner-applicat
>
## Setting an Embedded Ability (for System Applications Only)
## Setting an Embedded UIAbility (for System Applications Only)
The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
......@@ -58,7 +59,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i
}
```
4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component.
4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEnty** to the code path of the ExtensionAbility component.
```json
{
......@@ -66,11 +67,11 @@ To implement an embedded application, manually create a WindowExtensionAbility i
"extensionAbilities": [
{
"name": "WindowExtAbility",
"srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts",
"srcEnty": "./ets/WindowExtAbility/WindowExtAbility.ts",
"icon": "$media:icon",
"description": "WindowExtension",
"type": "window",
"visible": true,
"exported": true,
}
],
}
......@@ -78,7 +79,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i
```
## Starting an Embedded Ability (for System Applications Only)
## Starting an Embedded UIAbility (for System Applications Only)
System applications can load the created WindowExtensionAbility through the AbilityComponent.
......
......@@ -21,13 +21,13 @@ The key-value (KV) database stores data in the form of KV pairs. You can use KV
The following table lists the APIs used for KV data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
| API| Description|
| API| Description|
| -------- | -------- |
| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.|
| getKVStore&lt;T&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void | Creates and obtains a KV store of the specified type.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void | Adds a KV pair of the specified type to this KV store.|
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void | Obtains the value of the specified key.|
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a KV pair based on the specified key.|
| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.|
| getKVStore&lt;T&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void | Creates and obtains a KV store of the specified type.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void | Adds a KV pair of the specified type to this KV store.|
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void | Obtains the value of the specified key.|
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a KV pair based on the specified key.|
## How to Develop
......@@ -35,10 +35,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
1. Create a **KvManager** instance to manage database objects.
Example:
Stage model:
```js
// Import the module.
import distributedKVStore from '@ohos.data.distributedKVStore';
......@@ -69,7 +68,7 @@ The following table lists the APIs used for KV data persistence. Most of the API
FA model:
```js
// Import the module.
import distributedKVStore from '@ohos.data.distributedKVStore';
......@@ -93,14 +92,13 @@ The following table lists the APIs used for KV data persistence. Most of the API
```
2. Create and obtain a KV store.
Example:
```js
try {
const options = {
createIfMissing: true, // Whether to create a KV store when the database file does not exist. By default, a KV store is created.
createIfMissing: true, // Whether to encrypt database files. By default, database files are not encrypted.
encrypt: false, // Whether to encrypt the KV store. By default, KV stores are not encrypted.
backup: false, // Whether to back up database files. By default, the database files are backed up.
autoSync: true, // Whether to automatically synchronize database files. The value **true** means to automatically synchronize database files; the value **false** (default) means the opposite.
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // Type of the KV store to create. By default, a device KV store is created.
......@@ -121,9 +119,8 @@ The following table lists the APIs used for KV data persistence. Most of the API
```
3. Use **put()** to add data to the KV store.
Example:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
......@@ -145,9 +142,8 @@ The following table lists the APIs used for KV data persistence. Most of the API
> The **put()** method adds a KV pair if the specified key does not exists and changes the value if the the specified key already exists.
4. Use **get()** to obtain the value of a key.
Example:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
......@@ -172,9 +168,8 @@ The following table lists the APIs used for KV data persistence. Most of the API
```
5. Use **delete()** to delete the data of the specified key.
Example:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
......
......@@ -3,7 +3,7 @@
## When to Use
When creating a data table, you can set the table to support cross-device access. You can also use APIs to move the data to be accessed across devices to a distributed data.
You can synchronize the application data in a local RDB store on a device to other divices that form a Super Device.
## Basic Concepts
......@@ -51,14 +51,14 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
The following table lists the APIs for cross-device data synchronization of RDB stores. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
| API| Description|
| API| Description|
| -------- | -------- |
| setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void | Sets the distributed tables to be synchronized.|
| sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;): void | Synchronizes data across devices.|
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void | Subscribes to changes in the distributed data.|
| off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void | Unsubscribe from changes in the distributed data.|
| obtainDistributedTableName(device: string, table: string, callback: AsyncCallback&lt;string&gt;): void; | Obtains the table name on the specified device based on the local table name.|
| remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt; , callback: AsyncCallback&lt;ResultSet&gt;): void | Queries data from the RDB store of a remote device based on specified conditions.|
| setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void | Sets the distributed tables to be synchronized.|
| sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;): void | Synchronizes data across devices.|
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void | Subscribes to changes in the distributed data.|
| off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void | Unsubscribe from changes in the distributed data.|
| obtainDistributedTableName(device: string, table: string, callback: AsyncCallback&lt;string&gt;): void; | Obtains the table name on the specified device based on the local table name.|
| remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt; , callback: AsyncCallback&lt;ResultSet&gt;): void | Queries data from the RDB store of a remote device based on specified conditions.|
## How to Develop
......@@ -68,7 +68,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
> The data on a device can be synchronized only to the devices whose data security labels are not higher than the security level of the device. For details, see [Access Control Mechanism in Cross-Device Synchronization](sync-app-data-across-devices-overview.md#access-control-mechanism-in-cross-device-synchronization).
1. Import the module.
```js
import relationalStore from '@ohos.data.relationalStore';
```
......@@ -79,7 +79,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Create an RDB store and set a table for distributed synchronization.
```js
const STORE_CONFIG = {
name: 'RdbTest.db', // Database file name.
......@@ -95,7 +95,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
```
4. Synchronize data across devices. After **sync()** is called to trigger a synchronization, data is synchronized from the local device to all other devices on the network.
```js
// Construct the predicate object for synchronizing the distributed table.
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
......@@ -114,7 +114,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
```
5. Subscribe to changes in the distributed data. The data synchronization triggers the **observer** callback registered in **on()**. The input parameter of the callback is the ID of the device whose data changes.
```js
let observer = function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) {
......@@ -144,7 +144,7 @@ The following table lists the APIs for cross-device data synchronization of RDB
>
> **deviceIds** is obtained by using [devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are all system interfaces and available only to system applications.
```js
// Obtain device IDs.
import deviceManager from '@ohos.distributedHardware.deviceManager';
......
......@@ -36,14 +36,4 @@ Strong consistency has high requirements on distributed data management and may
## Access Control Mechanism in Cross-Device Synchronization
In the application data synchronization across devices, data access is controlled based on the device level and [data security label](access-control-by-device-and-data-level.md#data-security-labels). In principle, data can be synchronized only to the devices whose data security labels are not higher than the device's security level. The access control matrix is as follows:
|Device Security Level|Data Security Labels of the Synchornizable Device|
|---|---|
|SL1|S1|
|SL2|S1 to S2|
|SL3|S1 to S3|
|SL4|S1 to S4|
|SL5|S1 to S4|
For example, the security level of development boards RK3568 and Hi3516 is SL1. The database with data security label S1 can be synchronized with RK3568 and Hi3516, but the database with database labels S2-S4 cannot.
When data is synchronized across devices, access control is performed based on the device level and data security label. For details, see [Access Control Mechanism in Cross-Device Synchronization](access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-synchronization).
# FAQs
- [Ability Framework Development](faqs-ability.md)
- [Resource Management Development](faqs-globalization.md)
- [Ability Development](faqs-ability.md)
- [Bundle Management Development](faqs-bundle-management.md)
- [Resource Manager Development](faqs-globalization.md)
- [Common Event and Notification Development](faqs-event-notification.md)
- [Graphics and Image Development](faqs-graphics.md)
- [Graphics Development](faqs-graphics.md)
- [Window Management Development](faqs-window-manager.md)
- [Multimedia Development](faqs-multimedia.md)
- [Basic Security Capability Development](faqs-security.md)
- [Ability Access Control Development](faqs-ability-access-control.md)
- [Data Management Development](faqs-distributed-data-management.md)
- [File Management Development](faqs-file-management.md)
- [Network Management Development](faqs-network-management.md)
- [DFX Development](faqs-dfx.md)
- [Pan-Sensor Development](faqs-sensor.md)
- [Startup Development](faqs-startup.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md)
\ No newline at end of file
- [Distributed Device Development](faqs-distributed-device-profile.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md)
# Application Access Control Development
## Can the app listen for the permission change after its permission is modified in Settings?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
Third-party apps cannot listen for the permission change.
# Bundle Management Development
## How do I determine whether an application is a system application?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Use **bundleManager.getApplicationInfo** (available only for system applications) to obtain application information, and check the value of **systemApp** in the information. The application is a system application if the value is **true**.
**Reference**
[bundleManager](../reference/apis/js-apis-bundleManager.md)
## How do I obtain the version code and version name of an application?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Use **bundleManager.getBundleInfoForSelf\(\)** to obtain the bundle information, which contains the version code (specified by **BundleInfo.versionCode**) and version name (specified by **BundleInfo.versionName**) .
**Example**
```
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT;
try {
bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
const versionCode = data.versionCode;
const versionName = data.versionName;
hilog.info(0x0000, 'testTag', `successfully. versionCode: ${versionCode}, versionName: ${versionName}`);
}).catch(err => {
hilog.error(0x0000, 'testTag', 'failed. Cause: %{public}s', err.message);
});
} catch (err) {
hilog.error(0x0000, 'testTag', 'failed: %{public}s', err.message);
}
```
**Reference**
[getBundleInfoForSelf](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundleinfoforself)
## How do I obtain the bundle name of the current application?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
Obtain the bundle name from **UIAbilityContext.abilityInfo.bundleName**.
**Example**
```
import common from '@ohos.app.ability.common';
const context = getContext(this) as common.UIAbilityContext
console.log(`bundleName: ${context.abilityInfo.bundleName}`)
```
**Reference**
[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) and [AbilityInfo](../reference/apis/js-apis-bundleManager-abilityInfo.md#abilityinfo)
## How do I obtain the application version number, version name, and screen resolution?
Applicable to: OpenHarmony 3.2 Beta5
**Solution**
1. Obtain the bundle information from the **@ohos.bundle.bundleManager** module.
The bundle information contains the application version number and version name.
```
import bundleManager from '@ohos.bundle.bundleManager';
...
bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{
let versionName = bundleInfo.versionName; // Application version name.
let versionNo = bundleInfo.versionCode; // Application version number.
}).catch((error)=>{
console.error("get bundleInfo failed,error is "+error)
})
```
2. Obtain **screenDensity** from the **@ohos.app.ability.Configuration** module. **screenDensity** contains the screen resolution information.
```
import common from '@ohos.app.ability.common';
...
let context = getContext(this) as common.UIAbilityContext;
let screenDensity = context.config.screenDensity;
```
## How do I obtain the source file path of the current application?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
- Method 1: Use the application context to obtain the source file path.
```
this.uiAbilityContext.abilityInfo.applicationInfo.codePath
```
- Method 2: Use **@ohos.bundle.bundleManager** to obtain the source file path.
1. Import the **@ohos.bundle.bundleManager** module and use **bundleManager.getBundleInfoForSelf\(\)** to obtain the bundle information.
2. Obtain the source file path from **bundleInfo.appInfo.codePath**.
```
import bundleManager from '@ohos.bundle.bundleManager';
bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{
this.sourcePath = bundleInfo.appInfo.codePath;
})
```
## Can I obtain the HAP information of other applications from the current application?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
According to the OpenHarmony security design specifications, the SDK does not provide APIs for third-party applications to obtain bundle information (including but not limited to the application name and version number) of other applications.
# Bundle Management Development
## How do I obtain the version code and version name of an application?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use **bundle.getBundleInfo()** to obtain the bundle information, which contains the version code and version name.
Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo)
## How do I obtain the bundle name of an application?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Obtain the bundle name through **context.abilityInfo.bundleName**.
Reference: [AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md)
## How do I obtain an application icon?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use **bundle.getAbilityIcon** to obtain the application icon. To use this API, you must configure the permission **ohos.permission.GET_BUNDLE_INFO**.
Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo)
## How do I determine whether an application is a system application?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use **bundle.getApplicationInfo** to obtain the application information, and then check the value of **systemApp** in the information. The application is a system application if the value is **true**.
# Data Management Development
## How do I encrypt an RDB store?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Solution**
To encrypt an RDB store, set **encrypt** in **StoreConfig** to **true** when creating the RDB store.
**Reference**
[RDB Store](../reference/apis/js-apis-data-relationalStore.md#storeconfig)
## What if I failed to clear a table in an RDB store using TRUNCATE TABLE?
Applicable to: OpenHarmony SDK 3.2.9.2 (API version 9)
**Symptom**
An error is reported when the **TRUNCATE TABLE** statement is used to clear table data.
**Solution**
The RDB store uses SQLite and does not support the **TRUNCATE TABLE** statement. To clear a table in an RDB store, use the **DELETE** statement, for example, **DELETE FROM sqlite\_sequence WHERE name = 'table\_name'**.
## What data types does an RDB store support?
Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model
**Solution**
An RDB store supports data of the number, string, and Boolean types. The number type supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How do I save pixel map data to a database?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
Pixel map data fails to be stored.
**Solution**
Convert the pixel map data into an **ArrayBuffer** and save the **ArrayBuffer** to your database.
**Reference**
[readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1)
## How do I obtain RDB store files?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
The RDB store files are stored in **/data/app/el2/100/database/*Bundle_name*/entry/rdb/**. You can use the hdc command to copy the file from the directory and use a SQLite tool to open the file.
Example:
```
hdc file recv /data/app/el2/100/database/<bundleName>/entry/db/<tableName> ./<path>
```
## Do the OpenHarmony databases have a lock mechanism?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
The distributed data service (DDS), RDB store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
## What if I failed to use get() to obtain the data saved by @ohos.data.storage put()?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
After @ohos.data.storage **put()** is called to save data, **get()** is called to obtain the data. However, the data fails to be obtained.
**Solution**
The **put()** method provided by **@ohos.data.storage** saves data in the memory. When the application exits, the data in the memory will be cleared. If you want to persist the data, you need to call **flush()** or **flushSync()** after **put()**. After data is persisted, you can use **get()** to obtain the data after the application is restarted.
## What if a large text file fails to be saved in an RDB store?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
In API version 8, large text files cannot be saved in RDB stores.
**Solution**
In versions earlier than API version 9, the maximum length of a text file is 1024 bytes. If the text file exceeds 1024 bytes, it cannot be saved.
The limit on the text file size has been removed since API9 version.
# Distributed Device Development
## How do I view the IMEI of an OpenHarmony device?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Obtain the device IMEI from the **HUKS\_TAG\_ATTESTATION\_ID\_IMEI** parameter of the **HuksTag** API. [Reference](../reference/apis/js-apis-huks.md)
# File Management Development
## Does fileio.rmdir Delete Files Recursively?
## How do I obtain the path of system screenshots?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Yes. **fileio.rmdir** deletes files recursively.
**Solution**
## How Do I Create a File That Does Not Exist?
The screenshots are stored in **/storage/media/100/local/files/Pictures/Screenshots/**.
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
## How do I change the permissions on a directory to read/write on a device?
You can use **fileio.open(filePath, 0o100, 0o666)**. The second parameter **0o100** means to create a file if it does not exist. The third parameter **mode** must also be specified.
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
## What If "call fail callback fail, code: 202, data: json arguments illegal" Is Displayed?
**Symptom**
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
When the hdc command is used to send a file to a device, "permission denied" is displayed.
When the **fileio** module is used to copy files, the file path cannot start with "file:///".
**Solution**
## How Do I Read Files Outside the App Sandbox?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
If the input parameter of the **fileio** API is **path**, only the sandbox directory of the current app obtained from the context can be accessed. To access data in other directories such as the user data, images, and videos, open the file as the data owner and operate with the file descriptor (FD) returned.
For example, to read or write a file in Media Library, perform the following steps:
1. Use **getFileAssets()** to obtain the **fileAsset** object.
2. Use **fileAsset.open()** to obtain the FD.
3. Use the obtained FD as the **fileIo** API parameter to read and write the file.
## What If the File Contains Garbled Characters?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Read the file content from the buffer, and decode the file content using **util.TextDecoder**.
Example:
```
import util from '@ohos.util'
async function readFile(path) {
let stream = fileio.createStreamSync(path, "r+");
let readOut = await stream.read(new ArrayBuffer(4096));
let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
let buffer = new Uint8Array(readOut.buffer)
let readString = textDecoder.decode(buffer, { stream: false });
console.log ("[Demo] File content read: "+ readString);
}
```
## What Should I Do If There Is No Return Value or Error Captured After getAlbums Is Called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md).
1. Configure the required permission in the **module.json5** file.
```
"requestPermissions": [
{
"name": "ohos.permission.READ_MEDIA"
}
]
```
2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded.
```
import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts';
private requestPermissions() {
let permissionList: Array<string> = [
"ohos.permission.READ_MEDIA"
];
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, permissionList)
.then(data => {
console.info(`request permission data result = ${data.authResults}`)
})
.catch(err => {
console.error(`fail to request permission error:${err}`)
})
}
```
## What Do I Do If the App Crashes When FetchFileResult() Is Called Multiple Times?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Each time after the **FetchFileResult** object is called, call **FetchFileResult.close()** to release and invalidate the **FetchFileResult** object .
## What If An Error Is Reported by IDE When mediaLibrary.getMediaLibrary() Is Called in the Stage Model?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
In the stage model, use **mediaLibrary.getMediaLibrary(context: Context)** to obtain the media library instance.
## How Do I Sort the Data Returned by mediaLibrary.getFileAssets()?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use the **order** attribute in **[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)** to sort the data returned.
Run the **hdc shell mount -o remount,rw /** command to grant the read/write permissions.
# Graphics and Image Development
# Graphics Development
## Why do the isStatusBarLightIcon and isNavigationBarLightIcon attributes not take effect when window.setSystemBarProperties() is called?
## How do I obtain the DPI of a device?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attributes turn the font white when set to **true**. If **statusBarContentColor** is also set in **window.setSystemBarProperties()**, the **isStatusBarLightIcon** attribute does not take effect. Similarly, if **navigationBarContentColor** is set, the **isNavigationBarLightIcon** attribute does not take effect.
**Solution**
## How do I set the style of the system bar?
Import the **@ohos.display** module and call the **getDefaultDisplaySync\(\)** API.
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
**Example**
Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**.
```
import display from '@ohos.display';
let displayClass = null;
try {
displayClass = display.getDefaultDisplaySync();
console.info('Test densityDPI:' + JSON.stringify(displayClass.densityDPI));
} catch (exception) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception));
}
```
## How do I hide the status bar to get the immersive effect?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
1. Use the **onWindowStageCreate** to obtain a **windowClass** object.
```ts
onWindowStageCreate(windowStage) {
// When the main window is created, set the main page for this ability.
console.log("[Demo] EntryAbility onWindowStageCreate")
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window.')
return;
}
// Obtain a windowClass object.
globalThis.windowClass = data;
})
}
```
2. Enable the full-screen mode for the window and hide the status bar.
```ts
globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
});
```
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
**Solution**
1. Use **onWindowStageCreate** to obtain a **windowClass** object.
```
onWindowStageCreate(windowStage) {
// When the main window is created, set the main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window.')
return;
}
// Obtain a windowClass object.
globalThis.windowClass = data;
})
}
```
2. Enable the full-screen mode for the window and hide the status bar.
```
globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
});
```
## How do I obtain the window width and height?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Applicable to: OpenHarmony SDK 3.2 Beta5 (API version 9, stage model)
Use **window.getProperties()** to obtain the window properties. The **windowRect** field in the properties specifies the window width and height.
**Solution**
Example:
Import the **@ohos.window** module, obtain a **Window** object, and use **getWindowProperties\(\)** of the object to obtain the window properties. The **windowRect** field in the properties specifies the window width and height.
**Example**
```ts
let promise = windowClass.getProperties();
promise.then((data)=> {
console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect));
}).catch((err)=>{
console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err));
});
```
## How do I set the color of the system bar?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Refer to the following code:
```ts
window.getTopWindow(globalThis.mainContext).then(win => {
var systemBarProperties = {
statusBarColor: '#19B6FF', // Set the background color of the status bar.
navigationBarColor: '#19B6FF', // Set the background color of the navigation bar.
isStatusBarLightIcon: false, // Set the icon on the status bar not to be highlighted.
isNavigationBarLightIcon: true, // Set the icon on the navigation bar to be highlighted.
statusBarContentColor: '#0D0500', // Set the text color of the status bar.
navigationBarContentColor: '#FFA500' // Set the text color of the navigation bar.
};
win.setSystemBarProperties(systemBarProperties).catch(err => {
INDEX_LOGGER.info(`set System Bar Properties failed:${err}`)
})
})
.catch(err => {
INDEX_LOGGER.info(`get top window failed:${err}`)
})
import window from '@ohos.window';
let windowClass = null;
try {
let promise = window.getLastWindow(this.context);
promise.then((data)=> {
// Obtain a Window object.
windowClass = data;
try {
// Obtain the window properties.
let properties = windowClass.getWindowProperties();
let rect = properties.windowRect;
// rect.width: window width; rect.height: window height.
} catch (exception) {
console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception));
}
console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
}).catch((err)=>{
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
});} catch (exception) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
}
```
# Multimedia Development
## How do I obtain the frame data of a camera when using the XComponent to display the preview output stream of the camera?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Symptom**
Currently, the API does not support real-time preview of the camera frame data. To obtain the frame data, you must bind an action, for example, photographing.
**Solution**
Create a dual-channel preview to obtain the frame data.
1. Use the XComponent to create a preview stream.
```
// Obtain a PreviewOutput instance.
const surfaceId = globalThis.mxXComponentController.getXComponentSurfaceld();
this.mPreviewOutput = await Camera.createPreviewOutput(surfaceld) ;
```
2. Use imageReceiver to listen for image information.
```
// Add dual-channel preview.
const fullWidth = this.mFullScreenSize.width;
const fullHeight = this.mFullScreenSize.height;
const imageReceiver = await image.createImageReceiver(fullwidth, fullHeight,
formatImage, capacityImage) ;
const photoSurfaceId = await imageReceiver.getReceivingSurfaceld();
this.mPreviewOutputDouble = await Camera.createPreviewOutput ( photoSurfaceld)
```
## How do I obtain the preview image of the front camera?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
1. Use the **@ohos.multimedia.camera** module to obtain the physical camera information.
```
let cameraManager = await camera.getCameraManager(context);
let camerasInfo = await cameraManager.getSupportedCameras();
let cameraDevice = this.camerasInfo[0];
```
2. Create and start the input stream channel of the physical camera.
```
let cameraInput = await cameraManager.createCameraInput(cameraDevice);
await this.cameraInput.open();
```
3. Obtain the output formats supported by the camera, and create a preview output channel based on the surface ID provided by the XComponent.
```
let outputCapability = await this.cameraManager.getSupportedOutputCapability(cameraDevice);
let previewProfile = this.outputCapability.previewProfiles[0];
let previewOutput = await cameraManager.createPreviewOutput(previewProfile, previewId);
```
4. Create a camera session, add the camera input stream and preview output stream to the session, and start the session. The preview image is displayed on the XComponent.
```
let captureSession = await cameraManager.createCaptureSession();
await captureSession.beginConfig();
await captureSession.addInput(cameraInput);
await captureSession.addOutput(previewOutput);
await this.captureSession.commitConfig()
await this.captureSession.start();
```
## How do I set the camera focal length?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
1. Check whether the camera is a front camera. A front camera does not support focal length setting.
2. Use **captureSession.getZoomRatioRange\(\)** to obtain the focal length range supported by the device.
3. Check whether the target focal length is within the range obtained. If yes, call **captureSession.setZoomRatio\(\)** to set the focal length.
## How do I play music in the background?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Symptom**
Music cannot be played in the background.
**Solution**
**AVSession** controls media playback. When a third-party application switches to the background or encounters a screen lock event, media playback is forcibly paused and the application is unaware of the pause. To enable the application to continue the playback in the background, request a continuous task and access the AVSession capability, which allows Control Panel to control the playback behavior of third-party applications.
**Reference**
[Continuous Task Development](../task-management/continuous-task-dev-guide.md)
[AVSession Development](../media/using-avsession-developer.md)
## What should I do when multiple video components cannot be used for playback?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Symptom**
A large number of video components are created. They cannot play media normally or even crash.
**Solution**
A maximum of 13 media player instances can be created.
## How do I invoke the image library directly?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
```
let want = {
bundleName: 'com.ohos.photos',
abilityName: 'com.ohos.photos.MainAbility',
parameters: {
uri: 'detail'
}
};
let context = getContext(this) as common.UIAbilityContext;
context.startAbility(want);
```
# Basic Security Capability Development
## What is the maximum number of bytes that can be encrypted at a time in AES GCM mode in HUKS?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Solution**
In HUKS, a maximum of 64 bytes can be encrypted at a time in AES GCM mode.
**Example**
```
/* Encrypt the key. */
await huks.init(srcKeyAlias, encryptOptions).then((data) => {
console.info(`test init data: ${JSON.stringify(data)}`);
handle = data.handle;
}).catch((err) => {
console.info('test init err information: ' + JSON.stringify(err));
});
encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice (0,64)); // Take 64 bytes.
await huks.update(handle, encryptOptions).then(async (data) => {
console.info(`test update data ${JSON.stringify(data)}`);
encryptUpdateResult = Array.from(data.outData);
}).catch((err) => {
console.info('test update err information: ' + err);
});
encryptOptions.inData = aesCipherStringToUint8Array(cipherInData.slice (64,80)); // Remaining data
```
## What if garbled characters are returned by **digest()** of **Md** in Crypto framework?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Symptom**
In the CryptoFramework, garbled characters are returned by **digest()** of **Md**.
**Solution**
The DataBlob returned by **digest()** is of the Uint8Array type and needs to be converted into a hexadecimal string before being printed. You can use the online MD5 encryption tool to verify the result.
# Pan-Sensor Development
## Are the APIs used for obtaining PPG and ECG sensor data open to individual developers?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
Data collected by the PPG and ECG sensors of wearable devices is personal privacy data. Therefore, relative APIs are not open to individual developers.
# Usage of Third- and Fourth-Party Libraries
## What does the following error message mean: "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed."
## How do I obtain available third-party libraries?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used.
The three-party and four-party libraries that can be obtained through ohpm are summarized in the [OpenHarmony-TPC/tpc_resource repository](https://gitee.com/openharmony-tpc/tpc_resource). You can access this repository, and find the desired component based on the directory index.
## Can I transfer project-level dependencies?
## Which third-party libraries are related to network requests?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
For example, if project A depends on project B and project B depends on project C, can project A directly use the APIs provided by project C?
The following third-party libraries are related to network requests: [Axios](https://gitee.com/openharmony-sig/axios), httpclient, and okdownload. For details, see the [OpenHarmony-TPC/tpc_resource repository](https://gitee.com/openharmony-tpc/tpc_resource).
No. Project A cannot directly use the APIs provided by project C. The project packing tool NPM does not support dependency transfer. To use the APIs provided by project C, you can add the dependency of project C to project A.
## How do I use ohpm to import third- and fourth-party libraries?
## How do I obtain available third-party libraries?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
**Solution**
For details, see [Third-Party Components That Can Be Directly Used on OpenHarmony](https://gitee.com/openharmony-sig/third_party_app_libs).
- Method 1:
1. Open the **Terminal** window and run the following command to go to the **entry** directory:
## Which third-party libraries are related to network requests?
```
cd entry
```
2. Run the following command to install a third-party library, for example, **dayjs**:
```
ohpm install dayjs
```
3. Add the following statement in the .js file to import the third-party library:
```
import dayjs from 'dayjs';
```
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The [Axios](https://gitee.com/openharmony-sig/axios) library is related to network requests.
## How do I use NPM to import third- and fourth-party libraries?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
- Method 1:
1. Open the **Terminal** window and run the following command to go to the **entry** directory:
```
cd entry
```
2. Run the following command to install a third-party package, for example, **dayjs**:
```
npm install dayjs --save
```
3. Add the following statement in the .js file to import the package:
```
import dayjs from 'dayjs';
```
- Method 2:
1. Enter the **entry** directory of the project and open the **package.json** file.
2. Write the third-party NPM package to be installed (for example, **dayjs**) in the **package.json** file.
```
{
"dependencies": {
"dayjs": "^1.10.4",
- Method 2:
1. Enter the **entry** directory of the project and open the **oh-package.json5** file.
2. Write the third-party library to be installed (for example, **dayjs**) in the **oh-package.json5** file.
```
{
"dependencies": {
"dayjs": "^1.10.4",
}
}
}
```
3. Open the **Terminal** window and run the following command to go to the **entry** directory:
```
cd entry
```
4. Run the following command to install NPM:
```
npm install
```
5. Add the following statement in the .js file to import the package:
```
import dayjs from 'dayjs';
```
```
3. Open the **Terminal** window and run the following command to go to the **entry** directory:
```
cd entry
```
4. Run the following command to install the third-party library:
```
ohpm install
```
5. Add the following statement in the .js file to import the third-party library:
```
import dayjs from 'dayjs';
```
# Window Management Development
## How do I obtain the height of the status bar and navigation bar?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Before the window content is loaded, enable listening for the **systemAvoidAreaChange** event.
**Example**
```
// MainAbility.ts
import window from '@ohos.window';
/**
* Set the immersive window and obtain the height of the status bar and navigation bar.
* @param mainWindow Indicates the main window.
*/
async function enterImmersion(mainWindow: window.Window) {
mainWindow.on("systemBarTintChange", (data) => {
let avoidAreaRect = data.regionTint[0].region; // data.regionTint is an array that contains the rectangle coordinates of the status bar and navigation bar.
})
await mainWindow.setFullScreen(true)
await mainWindow.setSystemBarEnable(["status", "navigation"])
await mainWindow.systemBarProperties({
navigationBarColor: "#00000000",
statusBarColor: "#00000000",
navigationBarContentColor: "#FF0000",
statusBarContentColor: "#FF0000"
})
}
export default class MainAbility extends Ability {
// Do something.
async onWindowStageCreate(windowStage: window.WindowStage) {
let mainWindow = await windowStage.getMainWindow()
await enterImmersion(mainWindow)
windowStage.loadContent('pages/index')
}
// Do something.
}
```
## How do I hide the status bar on the top of an application?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Use **setWindowSystemBarEnable** in the **onWindowStageCreate** lifecycle callback of UIAbility.
**Example**
```
onWindowStageCreate(windowStage){
windowStage.getMainWindowSync().setWindowSystemBarEnable([])
......
}
```
**Reference**
[Window](../reference/apis/js-apis-window.md)
......@@ -73,7 +73,7 @@ The following figure shows the application file directories. The path of a file
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.|
| files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.<br>This directory is cleared when the application is uninstalled.|
| cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.<br>This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. The user can also clear this directory by using a system space management application. <br>The application needs to check whether the file still exists and determine whether to cache the file again.|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md).|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.|
The application file paths are used in the following scenarios:
......@@ -92,5 +92,3 @@ The following figure shows the application file directories. The path of a file
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory<br>
Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used.
<!--no_check-->
\ No newline at end of file
......@@ -23,6 +23,3 @@ The file systems can be classified into the following types based on the file st
**Figure 1** Files in an OS
![File classification model](figures/file-classification-model.png)
<!--no_check-->
\ No newline at end of file
......@@ -63,7 +63,11 @@ The **FilePicker** provides the following interfaces by file type:
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents.
After the documents are selected successfully, a result set containing the file URIs is returned. Further operations can be performed on the documents based on the file URIs.
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
......@@ -80,6 +84,32 @@ The **FilePicker** provides the following interfaces by file type:
})
```
> **NOTE**
>
> Currently, **DocumentSelectOptions** does not provide the method for obtaining the file name. To obtain the file name, use **startAbilityForResult()**.
```ts
let config = {
action: 'ohos.want.action.OPEN_FILE',
parameters: {
startMode: 'choose',
}
}
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// Obtain the URI of the document.
let select_item_list = result.want.parameters.select_item_list;
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
## Selecting an Audio File
1. Import the **FilePicker** module.
......
# Setting the Security Level of a Distributed File
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data and Device Security Classification](../database/access-control-by-device-and-data-level.md).
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data Security Labels and Device Security Levels](../database/access-control-by-device-and-data-level.md).
## Available APIs
......@@ -39,4 +39,3 @@ securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
});
```
<!--no_check-->
\ No newline at end of file
......@@ -6,13 +6,13 @@ The file of an application can be shared with another application based on the f
- You can also use **open()** of the ohos.file.fs module to share an application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs.
You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-files).
You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-application-files).
## File URI Specifications
The file URIs are in the following format:
file://&lt;bundleName&gt;/&lt;path&gt;/\#networkid=&lt;networkid&gt;
file://&lt;bundleName&gt;/&lt;path&gt;
- **file**: indicates a file URI.
......@@ -20,8 +20,6 @@ The file URIs are in the following format:
- *path*: specifies the application sandbox path of the file.
- *networkid* (optional): specifies the device to which the file belongs in a distributed file system. Leave this parameter unspecified if the file location does not need to be set.
## Sharing a File with Another Application
Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path).
......
......@@ -88,7 +88,7 @@ To enable an audio and video application to access the AVSession service as a pr
```ts
// It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above.
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let wantAgentInfo: {
let wantAgentInfo = {
wants: [
{
bundleName: "com.example.musicdemo",
......
......@@ -23,9 +23,9 @@ In this example, the basic composition of ArkTS is as follows.
- [Custom component](arkts-create-custom-components.md): reusable UI unit, which can be combined with other components, such as the struct **Hello** decorated by @Component.
- Built-in component: default basic or container component preset in ArkTS, which can be directly invoked, such as** \<Column>**,** \<Text>**, **\<Divider>**, and **\<Button>** components in the sample code.
- Built-in component: default basic or container component preset in ArkTS, which can be directly invoked, such as **\<Column>**, **\<Text>**, **\<Divider>**, and **\<Button>** components in the sample code.
- Attribute method: method used to configure component attributes, such as **fontSize()**, **width()**, **height()**, and **color()**. You can configure multiple attributes of a component in method chaining mode.
- Attribute method: method used to configure component attributes, such as **fontSize()**, **width()**, **height()**, and **backgroundColor()**. You can configure multiple attributes of a component in method chaining mode.
- Event method: method used to add the logic for a component to respond to an event. In the sample code, **onClick()** following **Button** is an event method. You can configure response logic for multiple events in method chaining mode.
......
......@@ -77,7 +77,7 @@ Pre-loading is triggered after the first frame of the newly accessed module is r
"module": {
"name": "entry",
"type": "entry",
"srcEnty": "./ets/Application/MyAbilityStage.ts",
"srcEntry": "./ets/Application/MyAbilityStage.ts",
"description": "$string:entry_desc",
"mainElement": "MainAbility",
"deviceTypes": [
......@@ -97,7 +97,7 @@ Pre-loading is triggered after the first frame of the newly accessed module is r
"abilities": [
{
"name": "MainAbility",
"srcEnty": "./ets/MainAbility/MainAbility.ts",
"srcEntry": "./ets/MainAbility/MainAbility.ts",
"description": "$string:MainAbility_desc",
"icon": "$media:icon",
"label": "$string:MainAbility_label",
......@@ -169,7 +169,7 @@ import router from '@ohos.router';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State message: string = 'Hello World';
build() {
Row() {
......@@ -209,10 +209,10 @@ struct Index {
```
The input parameter **url** of the **router.pushUrl** API is as follows:
```ets
```ts
'@bundle:com.example.hmservice/library/ets/pages/menu'
```
The **url** content template is as follows:
```ets
```ts
'@bundle:bundle name/module name/path/page file name (without the extension .ets)'
```
# In-Application HSP Development
An in-application Harmony Shared Package (HSP) is a file used for code and resource sharing within an application (called the host application) and can only be invoked by a HAP or HSP of the same application.
The in-application HSP is released with the Application Package (App Pack) of the host application and has the same bundle name and lifecycle as the host application.
The in-application HSP is released with the Application Package (App Pack) of the host application, shares a process with the host application, and has the same bundle name and lifecycle as the host application.
## Developing an In-Application HSP
......@@ -151,3 +151,59 @@ struct Index {
}
}
```
### Redirecting to a Page in Another Bundle
If you want to add a button in the **entry** module to jump to the menu page (**library/src/main/ets/pages/menu.ets**) in the **library** module, you can write the following code in the **entry/src/main/ets/MainAbility/Index.ets** file of the **entry** module:
```ts
import router from '@ohos.router';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Add a button to respond to user clicks.
Button() {
Text('click to menu')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
// Bind click events.
.onClick(() => {
router.pushUrl({
url: '@bundle:com.example.hmservice/library/ets/pages/menu'
}).then(() => {
console.log("push page success");
}).catch(err => {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
})
.width('100%')
}
.height('100%')
}
}
}
```
The input parameter **url** of the **router.pushUrl** API is as follows:
```ets
'@bundle:com.example.hmservice/library/ets/pages/menu'
```
The **url** content template is as follows:
```ets
'@bundle:bundle name/module name/path/page file name (without the extension .ets)'
```
......@@ -20,7 +20,7 @@ The **module** tag contains the HAP configuration.
| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)|
| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)|
| colorMode | Color mode of the application. The options are as follows:<br>- **dark**: Resources applicable for the dark mode are used.<br>- **light**: Resources applicable for the light mode are used.<br>- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)|
| distroFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.|
| distributionFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.|
|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| Object array| Yes (initial value: left empty)|
| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)|
|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)|
......@@ -268,7 +268,7 @@ Note: The label displayed on the application details screen may be different fro
| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.<br>The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes.| String| No|
| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.<br>Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)|
| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)|
| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)|
| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)|
| launchType | Launch type of the ability. The value can be **standard** or **singleton**.<br>**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.<br>**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)|
| visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by other applications.<br>**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
......@@ -380,7 +380,7 @@ Example of the **abilities** attribute structure:
| -------- | -------- | -------- | -------- |
| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)|
| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)|
| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both.<br>The URI is specified by separate attributes of each part: &lt;scheme&gt;://&lt;host&gt;:&lt;port&gt;[&lt;path&gt;\|&lt;pathStartWith&gt;\|&lt;pathRegex&gt;]. <br>**scheme** is mandatory when the specification is of the URI type and is optional when the specification is of data type only.| Object array| Yes (initial value: left empty)|
| uris | Data specifications to be added to the want filter. The specification is a data type (using the **mimeType** attribute), a URI, or both a data type and a URI.<br>The URI is specified by separate attributes of each part: &lt;scheme&gt;://&lt;host&gt;:&lt;port&gt;[&lt;path&gt;\|&lt;pathStartWith&gt;\|&lt;pathRegex&gt;]. <br>**scheme** is mandatory when the specification is of the URI type and is optional when the specification is a data type. | Object array| Yes (initial value: left empty)|
## Internal Structure of the uris Attribute
......@@ -614,9 +614,9 @@ Example of the **forms** attribute structure:
]
```
## Internal Structure of the distroFilter Attribute
## Internal Structure of the distributionFilter Attribute
**Table 21** Internal structure of the distroFilter attribute
**Table 21** Internal structure of the distributionFilter attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
......
# Multi-HAP Design Objectives
- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, If you are developing a payment application and its home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the logic of the home screen for managing other modules in the entry-type HAP file, and implement specific modules in feature-type HAP files. The feature-type HAP files are independent. You can develop and test each of them separately, and then integrate them with the entry-type HAP file.
- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, if you are developing a payment application whose home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the HAP files as follows: (1) In the entry-type HAP file, implement the home screen logic for managing modules; (2) in feature-type HAP files, implement specific modules. The feature-type HAP files are independent of each other. You can develop and test each of them separately, and then integrate them with the entry-type HAP file.
- Flexible deployment: You can combine multiple HAP files and deploy them on different devices. Assume that an application contains one entry-type HAP file (**Entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. In this way, you can easily combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B.
- Flexible deployment: You can flexibly combine HAP files for device-specific deployment. Assume that an application contains one entry-type HAP file (**entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. This means that you can combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B.
- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of an application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent.
- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which reduces the size of the application package to some extent.
- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of your application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent.
......@@ -46,7 +46,7 @@ The command contains the following options:
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
$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-path patchs --out-path entry-default-unsigned.hqf --force true
```
The command contains the following options.
......
......@@ -18,7 +18,7 @@ Quick fix is a technical means provided by the OpenHarmony system for developers
<br>The preceding figure shows the structure of the quick fix package released by an OpenHarmony application.
* As shown in the figure, the quick fix package comes in two formats:
* .appqf (Application Quick Fix)
<br> There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage).
<br> There is a one-to-one mapping between the .appqf file and App Pack of an application. For details, see [Application Package Structure in Stage Model](application-package-structure-stage.md).
* The .appqf file is used to release OpenHarmony applications to the application market and cannot be directly installed on devices.
* An .appqf file consists of one or more .hqf (Harmony Ability Package Quick Fix) files, which are extracted from the .appqf file by the application market and then distributed to specific devices.
* The .appqf file must contain the developer's signature information before being released to the application market. For details about how to sign the file, see [hapsigner Overview](../security/hapsigntool-overview.md).
......
......@@ -8,13 +8,11 @@ Both the HAR and HSP are used to share code and resources and can contain code,
![in-app-hsp-har](figures/in-app-hsp-har.png)
The HSP is designed to solve the following issues with the HAR:
- When multiple HAPs reference the same HAR, the size of the App Pack swells.
- When multiple HAPs reference the same HAR, some state variables in the HAR cannot be shared.
The HSP aims to resolve the App Pack bloat resulting from multiple HAP files referencing the same HAR.
Restrictions on the HSP:
- The HSP and its invoking modules must be in the stage model.
- The HSP and its invoking modules must use the **esmodule **compilation mode.
- The HSP and its invoking modules must use the **esmodule** compilation mode.
- The HSP does not support the declaration of **abilities** and **extensionAbilities** in its configuration file.
The HSP can be classified as [in-application HSP](in-app-hsp.md) or inter-application HSP, which will be supported in later versions.
......@@ -41,6 +41,6 @@ To help you better understand the preceding basic concepts and application devel
1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio).
2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443).
2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/environment_config-0000001052902427-V3).
When you are done, follow the instructions in [Getting Started with ArkTS in Stage Model](start-with-ets-stage.md), [Getting Started with ArkTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](start-with-js-fa.md).
......@@ -5,18 +5,18 @@
>
> To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
>
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
> For best possible results, use [DevEco Studio 3.1 Beta2](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next.
![01](figures/01.png)
![createProject](figures/createProject.png)
2. In the project configuration page, set **Compile SDK** to **8** or **9** (in the latter case, you also need to set **Model** to **FA**) and **Language** to **ArkTS** and retain the default values for other parameters.
![02](figures/02.png)
![chooseFAModel_ets](figures/chooseFAModel_ets.png)
> **NOTE**
>
......@@ -27,6 +27,7 @@
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
4. After the project is created, in the **entry** > **build-profile.json5** file, change **runtimeOS** under **targets** to **OpenHarmony**, and click **Sync Now** in the upper right corner to start development.
## ArkTS Project Directory Structure (FA Model)
......@@ -41,11 +42,9 @@
- **src > main > ets > MainAbility > app.ets**: ability lifecycle file.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.ts**: application-level build script.
......@@ -291,7 +290,7 @@ You can implement page redirection through the [page router](../reference/apis/j
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png)
![signConfig](figures/signConfig.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001364054485](figures/en-us_image_0000001364054485.png). The display effect is shown in the figure below.
......
......@@ -5,18 +5,18 @@
>
> To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
>
> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
> For best possible results, use [DevEco Studio 3.1 Beta2](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development.
## Creating an ArkTS Project
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next.
![01](figures/01.png)
![createProject](figures/createProject.png)
2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, and retain the default values for other parameters.
![07](figures/07.png)
![chooseStageModel](figures/chooseStageModel.png)
> **NOTE**
>
......@@ -28,22 +28,24 @@
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
4. After the project is created, in the **entry** > **build-profile.json5** file, change **runtimeOS** under **targets** to **OpenHarmony**, and click **Sync Now** in the upper right corner to start development.
## ArkTS Project Directory Structure (Stage Model)
![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png)
- **AppScope** > **app.json5**: global configuration of your application.
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
- **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service.
- **src > main > ets > pages**: pages included in your application/service.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.ts**: application-level build script.
......@@ -123,7 +125,7 @@
- Create the second page file: In the **Project** window, choose **entry** > **src** > **main** > **ets**. Right-click the **pages** folder, choose **New** > **ArkTS File**, name the page **Second**, and click **Finish**. Below is the structure of the **Second** folder.
![09](figures/09.png)
![secondPage](figures/secondPage.png)
> **NOTE**
>
......@@ -281,7 +283,7 @@ You can implement page redirection through the [page router](../reference/apis/j
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png)
![signConfig](figures/signConfig.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001364054485](figures/en-us_image_0000001364054485.png). The display effect is shown in the figure below.
......
......@@ -3,18 +3,18 @@
> **NOTE**
>
> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
> For best possible results, use [DevEco Studio 3.1 Beta2](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development.
## Creating a JavaScript Project
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **Choose Your Ability Template** page, select **Application** (or **Atomic Service**, depending on your project), select **Empty Ability** as the template, and click Next.
![01](figures/01.png)
![createProject](figures/createProject.png)
2. In the project configuration page, set **Compile SDK** to **8** or **9** (in the latter case, you also need to set **Model** to **FA**) and **Language** to **JS** and retain the default values for other parameters.
![04](figures/04.png)
![chooseFAModel_js](figures/chooseFAModel_js.png)
> **NOTE**
>
......@@ -26,6 +26,8 @@
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
4. After the project is created, in the **entry** > **build-profile.json5** file, change **runtimeOS** under **targets** to **OpenHarmony**, and click **Sync Now** in the upper right corner to start development.
## JavaScript Project Directory Structure
......@@ -40,7 +42,7 @@
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Limitations and Access](../ui/js-framework-resource-restriction.md).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
......@@ -226,7 +228,7 @@ You can implement page redirection through the [page router](../reference/apis/j
2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png)
![signConfig](figures/signConfig.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001364054485](figures/en-us_image_0000001364054485.png). The display effect is shown in the figure below.
......
......@@ -15,15 +15,15 @@ import ability from '@ohos.ability.ability';
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | No | Level-2 module **DataAbilityHelper**. |
| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.|
| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | No | Level-2 module **DataAbilityOperation**.|
| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | No | Level-2 module **DataAbilityResult**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.|
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.|
| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | No | Level-2 module **StartAbilityParameter**.|
| Name | Type | Description |
| ----------- | -------------------- | ------------------------------------------------------------ |
| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Level-2 module **DataAbilityHelper**. |
| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | Level-2 module **PacMap**.|
| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | Level-2 module **DataAbilityOperation**.|
| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module **DataAbilityResult**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.|
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.|
| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Level-2 module **StartAbilityParameter**.|
**Example**
```ts
......
......@@ -3,7 +3,7 @@
The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground.
> **NOTE**
>
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -32,7 +32,7 @@ Registers a listener to observe the mission status.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.|
| listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Listener to register.|
**Return value**
......@@ -79,7 +79,7 @@ export default class EntryAbility extends UIAbility {
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
// The main window is created. Set a main page for this ability.
console.log('[Demo] EntryAbility onWindowStageCreate');
try {
listenerId = missionManager.on('mission', listener);
......@@ -107,7 +107,7 @@ export default class EntryAbility extends UIAbility {
off(type: 'mission', listenerId: number, callback: AsyncCallback&lt;void&gt;): void;
Deregisters a mission status listener.
Deregisters a mission status listener. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
......@@ -122,6 +122,14 @@ Deregisters a mission status listener.
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300002 | Input error. The specified mission listener does not exist. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -161,7 +169,7 @@ export default class EntryAbility extends UIAbility {
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
// The main window is created. Set a main page for this ability.
console.log('[Demo] EntryAbility onWindowStageCreate');
try {
listenerId = missionManager.on('mission', listener);
......@@ -205,9 +213,17 @@ Deregisters a mission status listener. This API uses a promise to return the res
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300002 | Input error. The specified mission listener does not exist. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -248,7 +264,7 @@ export default class EntryAbility extends UIAbility {
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
// The main window is created. Set a main page for this ability.
console.log('[Demo] EntryAbility onWindowStageCreate');
try {
listenerId = missionManager.on('mission', listener);
......@@ -631,6 +647,14 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -673,9 +697,17 @@ Locks a given mission. This API uses a promise to return the result.
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -719,6 +751,14 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -761,9 +801,17 @@ Unlocks a given mission. This API uses a promise to return the result.
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -852,9 +900,9 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
......@@ -916,9 +964,9 @@ Clears all unlocked missions. This API uses a promise to return the result.
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
......@@ -949,6 +997,14 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -991,6 +1047,14 @@ Switches a given mission to the foreground, with the startup parameters for the
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -1034,9 +1098,17 @@ Switches a given mission to the foreground, with the startup parameters for the
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......
......@@ -62,6 +62,25 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500002 | Copy file failed, maybe not exist or inaccessible. |
| 18500008 | Internal error. |
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9). The table below lists the possible error codes and messages.
| ID| Error Message|
| ------- | -------- |
| 18500003 | Deploy hqf failed. |
| 18500004 | Switch hqf failed. |
| 18500005 | Delete hqf failed. |
| 18500006 | Load patch failed. |
| 18500007 | Unload patch failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
> **NOTE**
>
> The file path passed in the API must be an application sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](js-apis-bundle-BundleInstaller.md#obtaining-the-sandbox-path). The path mapped to the device is **/proc/<*applicationProcessId*>/root/*sandboxPath***.
......@@ -109,6 +128,25 @@ Applies a quick fix patch. This API uses a promise to return the result.
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500002 | Copy file failed, maybe not exist or inaccessible. |
| 18500008 | Internal error. |
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9). The table below lists the possible error codes and messages.
| ID| Error Message|
| ------- | -------- |
| 18500003 | Deploy hqf failed. |
| 18500004 | Switch hqf failed. |
| 18500005 | Delete hqf failed. |
| 18500006 | Load patch failed. |
| 18500007 | Unload patch failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -145,6 +183,15 @@ Obtains the quick fix information of the application. This API uses an asynchron
| bundleName | string | Yes|Bundle name. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500001 | The bundle is not exist. |
| 18500008 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -188,6 +235,15 @@ Obtains the quick fix information of the application. This API uses a promise to
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500001 | The bundle is not exist. |
| 18500008 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......
# @ohos.app.ability.wantAgent (WantAgent)
The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future.
The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object.
> **NOTE**
>
......@@ -24,9 +24,18 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description |
| -------- | -------------------------- | ---- | ----------------------- |
| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. |
| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. |
| callback | AsyncCallback\<WantAgent\> | Yes | Callback used to return the **WantAgent** object.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
......@@ -93,6 +102,15 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. If
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<WantAgent\> | Promise used to return the **WantAgent** object.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
......@@ -153,16 +171,25 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous
| agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<string\> | Yes | Callback used to return the bundle name.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
//getWantAgent callback
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
......@@ -234,16 +261,25 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<string\> | Promise used to return the bundle name.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
//WantAgentInfo object
// WantAgentInfo object
let wantAgentInfo = {
wants: [
{
......@@ -302,13 +338,22 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal
| agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<number\> | Yes | Callback used to return the user ID.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// getWantAgent callback
......@@ -383,13 +428,22 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<number\> | Promise used to return the user ID.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// WantAgentInfo object
......@@ -453,13 +507,23 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba
| agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// getWantAgent callback
......@@ -536,13 +600,23 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<Want\> | Promise used to return the want.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// WantAgentInfo object
......@@ -604,13 +678,22 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return
| agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// getWantAgent callback
......@@ -685,13 +768,22 @@ Cancels a **WantAgent** object. This API uses a promise to return the result.
| --------------- | ------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// WantAgentInfo object
......@@ -751,15 +843,16 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description |
| ----------- | ----------------------------- | ---- | ------------------------------- |
| agent | WantAgent | Yes | Target **WantAgent** object. |
| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. |
| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. |
| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.|
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// getWantAgent callback
......@@ -823,7 +916,7 @@ try {
equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\<boolean\>): void
Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result.
Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -841,7 +934,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent1;
let wantAgent2;
......@@ -902,7 +995,7 @@ try {
equal(agent: WantAgent, otherAgent: WantAgent): Promise\<boolean\>
Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result.
Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -925,7 +1018,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent1;
let wantAgent2;
......@@ -987,12 +1080,22 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron
| agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the operation type.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// WantAgentInfo object
......@@ -1057,12 +1160,22 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<number> | Promise used to return the operation type.|
**Error codes**
| ID | Error Message |
|-----------|--------------------|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
// WantAgent object
let wantAgent;
// WantAgentInfo object
......@@ -1153,4 +1266,3 @@ try {
| finalCode | number | Yes | Request code that triggers the **WantAgent** object.|
| finalData | string | Yes | Final data collected by the common event. |
| extraInfo | {[key: string]: any} | No | Extra information. |
......@@ -48,20 +48,17 @@ Creates a **FormBindingData** object.
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
context.getOrCreateLocalDir((err,data)=>{
let path=data+'/xxx.jpg';
let fd = fileio.openSync(path);
import formBindingData from '@ohos.app.form.formBindingData';
import fs from '@ohos.file.fs';
try {
let fd = fs.openSync('/path/to/form.png');
let obj = {
'temperature': '21°',
'formImages': {'image': fd}
'formImages': { 'image': fd }
};
try {
formBindingData.createFormBindingData(obj);
} catch (error) {
console.log(`catch err->${JSON.stringify(err)}`);
}
})
formBindingData.createFormBindingData(obj);
} catch (error) {
console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
# @ohos.app.form.formProvider (FormProvider)
# @ohos.app.form.formProvider (formProvider)
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release.
......@@ -32,19 +32,26 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
| 16501001 | The ID of the form to be operated does not exist. |
| 16501002 | The number of forms exceeds upper bound. |
| 16501003 | The form can not be operated by the current application. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
```ts
var formId = '12400633174999288';
try {
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
formProvider.setFormNextRefreshTime(formId, 5, (error) => {
if (error) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
} else {
console.log(`formProvider setFormNextRefreshTime success`);
return;
}
console.log(`formProvider setFormNextRefreshTime success`);
});
} catch (error) {
console.log('error' + JSON.stringify(error))
......@@ -77,7 +84,14 @@ Sets the next refresh time for a widget. This API uses a promise to return the r
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
| 16501001 | The ID of the form to be operated does not exist. |
| 16501002 | The number of forms exceeds upper bound. |
| 16501003 | The form can not be operated by the current application. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -115,7 +129,13 @@ Updates a widget. This API uses an asynchronous callback to return the result.
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
| 16501001 | The ID of the form to be operated does not exist. |
| 16501003 | The form can not be operated by the current application. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -124,12 +144,12 @@ import formBindingData from '@ohos.application.formBindingData';
var formId = '12400633174999288';
try {
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
formProvider.updateForm(formId, obj, (error, data) => {
formProvider.updateForm(formId, obj, (error) => {
if (error) {
console.log('formProvider updateForm, error:' + JSON.stringify(error));
} else {
console.log(`formProvider updateForm success`);
return;
}
console.log(`formProvider updateForm success`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
......@@ -162,7 +182,13 @@ Updates a widget. This API uses a promise to return the result.
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
| 16501001 | The ID of the form to be operated does not exist. |
| 16501003 | The form can not be operated by the current application. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -196,11 +222,13 @@ Obtains the application's widget information on the device. This API uses an asy
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -210,9 +238,9 @@ try {
formProvider.getFormsInfo((error, data) => {
if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
return;
}
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
......@@ -238,7 +266,10 @@ Obtains the application's widget information that meets a filter criterion on th
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -253,9 +284,9 @@ try {
formProvider.getFormsInfo(filter, (error, data) => {
if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
return;
}
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
......@@ -274,7 +305,7 @@ Obtains the application's widget information on the device. This API uses a prom
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | No| Filter criterion.|
| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | No| Filter criterion. |
**Return value**
......@@ -287,7 +318,10 @@ Obtains the application's widget information on the device. This API uses a prom
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -324,15 +358,19 @@ Requests to publish a widget carrying data to the widget host. This API uses an
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>'ohos.extra.param.key.form_dimension'<br>'ohos.extra.param.key.form_name'<br>'ohos.extra.param.key.module_name' |
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 202 | The application is not a system application. |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -351,9 +389,9 @@ try {
formProvider.requestPublishForm(want, obj, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
return;
}
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
......@@ -381,8 +419,12 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c
| Error Code ID| Error Message|
| -------- | -------- |
| 202 | The application is not a system application. |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -399,9 +441,9 @@ try {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
return;
}
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
......@@ -424,7 +466,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Name | Type | Mandatory| Description |
| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>'ohos.extra.param.key.form_dimension'<br>'ohos.extra.param.key.form_name'<br>'ohos.extra.param.key.module_name' |
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. |
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. By default, no value is passed, indicating that no data is provided. |
**Return value**
......@@ -436,8 +478,12 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Error Code ID| Error Message|
| -------- | -------- |
| 202 | The application is not a system application. |
| 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
| 16500050 | An IPC connection error happened. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
......@@ -477,6 +523,16 @@ Checks whether a widget can be published to the widget host. This API uses an as
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether the widget can be published to the widget host.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 202 | The application is not a system application. |
| 401 | If the input parameter is not valid parameter. |
| 16500050 | An IPC connection error happened. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
```ts
......@@ -530,6 +586,15 @@ Checks whether a widget can be published to the widget host. This API uses a pro
| :------------ | :---------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return whether the widget can be published to the widget host.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 202 | The application is not a system application. |
| 16500050 | An IPC connection error happened. |
| 16501000 | An internal functional error occurred. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).||
**Example**
```ts
......
# @ohos.util.ArrayList (Linear Container ArrayList)
> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
**ArrayList** is a linear data structure that is implemented based on arrays. **ArrayList** can dynamically adjust the capacity based on project requirements. It increases the capacity by 50% each time.
Similar to **ArrayList**, **[Vector](js-apis-vector.md)** is also implemented based on arrays and can dynamically adjust the capacity. It increases the capability by 100% each time.
......@@ -14,6 +11,11 @@ When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is mor
This topic uses the following to identify the use of generics:
- T: Type
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
......@@ -160,9 +162,8 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts
let arrayList = new ArrayList();
let result = arrayList.has("squirrel");
arrayList.add("squirrel");
let result1 = arrayList.has("squirrel");
let result = arrayList.has("squirrel");
```
### getIndexOf
......@@ -535,9 +536,7 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
let result1 = arrayList.subArrayList(2, 4);
let result2 = arrayList.subArrayList(4, 3);
let result3 = arrayList.subArrayList(2, 6);
let result = arrayList.subArrayList(2, 4);
```
### clear
......
......@@ -483,8 +483,8 @@ Enumerates the audio channels.
| Name | Value | Description |
| --------- | -------- | -------- |
| CHANNEL_1 | 0x1 << 0 | Mono.|
| CHANNEL_2 | 0x1 << 1 | Dual-channel.|
| CHANNEL_1 | 0x1 << 0 | Channel 1. |
| CHANNEL_2 | 0x1 << 1 | Channel 2. |
## AudioSamplingRate<sup>8+</sup>
......
......@@ -389,7 +389,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message |
| -------- | ------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**Example**
......@@ -575,7 +574,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message |
| -------- | --------------------------------------|
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**Example**
......@@ -725,14 +723,6 @@ Obtains the information about all bundles based on the given bundle flags. This
| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain. |
| callback | AsyncCallback<Array\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of bundle information obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ---------------------------------- |
| 17700004 | The specified user ID is not found. |
**Example**
```ts
......@@ -872,14 +862,6 @@ Obtains the information about all applications based on the given application fl
| appFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. |
| callback | AsyncCallback<Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of application information obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ---------------------------------- |
| 17700004 | The specified user ID is not found. |
**Example**
```ts
......@@ -1038,7 +1020,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| -------- | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700003 | The specified ability is not found. |
| 17700004 | The specified userId is invalid. |
| 17700026 | The specified bundle is disabled. |
| 17700029 | The specified ability is disabled. |
......@@ -1235,7 +1216,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| -------- | -------------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700003 | The specified extensionAbility is not found. |
| 17700004 | The specified userId is invalid. |
| 17700026 | The specified bundle is disabled. |
**Example**
......@@ -2159,7 +2139,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message |
| -------- | --------------------------------------|
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**Example**
......
......@@ -36,12 +36,13 @@ Publishes a common event. This API uses an asynchronous callback to return the r
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
|ID |Error Message |
|-----------|--------------------|
|1500004 |not System services or System app|
|1500007 |message send error|
|1500008 |CEMS error|
|1500009 |system error|
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -80,17 +81,16 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
| callback | syncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
|ID |Error Message |
|-----------|--------------------|
|1500004 |not System services or System app|
|1500007 |message send error|
|1500008 |CEMS error|
|1500009 |system error|
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
```ts
// Attributes of a common event.
var options = {
......@@ -137,12 +137,14 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
|ID |Error Message |
|-----------|--------------------|
|1500004 |not System services or System app|
|1500007 |message send error|
|1500008 |CEMS error|
|1500009 |system error|
| ID| Error Message |
| -------- | ----------------------------------- |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -189,16 +191,17 @@ Publishes a common event with given attributes to a specific user. This API uses
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
|ID |Error Message |
|-----------|--------------------|
|1500004 |not System services or System app|
|1500007 |message send error|
|1500008 |CEMS error|
|1500009 |system error|
| ID| Error Message |
| -------- | ----------------------------------- |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
```ts
// Attributes of a common event.
var options = {
......@@ -243,6 +246,14 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. |
| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
**Example**
......@@ -293,6 +304,14 @@ Creates a subscriber. This API uses a promise to return the result.
| --------------------------------------------------------- | ---------------- |
| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
**Example**
```ts
......@@ -334,6 +353,17 @@ Subscribes to common events. This API uses an asynchronous callback to return th
| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. |
| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 801 | capability not supported. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
**Example**
```ts
......@@ -395,6 +425,17 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. |
| callback | AsyncCallback\<void> | No | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 801 | capability not supported. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
**Example**
```ts
......@@ -465,6 +506,19 @@ Obtains the result code of this common event. This API uses an asynchronous call
| -------- | ---------------------- | ---- | ------------------ |
| callback | AsyncCallback\<number> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 201 | The application dose not have permission to call the interface. |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not system service. |
| 1500007 | The message send error. |
| 1500008 | The CEMS error. |
**Example**
```ts
......@@ -495,6 +549,19 @@ Obtains the result code of this common event. This API uses a promise to return
| ---------------- | -------------------- |
| Promise\<number> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 201 | The application dose not have permission to call the interface. |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not system service. |
| 1500007 | The message send error. |
| 1500008 | The CEMS error. |
**Example**
```ts
......
......@@ -156,9 +156,8 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts
let deque = new Deque();
let result = deque.has("squirrel");
deque.insertFront("squirrel");
let result1 = deque.has("squirrel");
let result = deque.has("squirrel");
```
### popFirst
......
......@@ -119,9 +119,8 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts
let hashMap = new HashMap();
let result = hashMap.hasKey("squirrel");
hashMap.set("squirrel", 123);
let result1 = hashMap.hasKey("squirrel");
let result = hashMap.hasKey("squirrel");
```
......@@ -157,9 +156,8 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts
let hashMap = new HashMap();
let result = hashMap.hasValue(123);
hashMap.set("squirrel", 123);
let result1 = hashMap.hasValue(123);
let result = hashMap.hasValue(123);
```
......@@ -230,6 +228,7 @@ let hashMap = new HashMap();
hashMap.set("squirrel", 123);
hashMap.set("sparrow", 356);
let newHashMap = new HashMap();
newHashMap.set("newMap", 99);
hashMap.setAll(newHashMap);
```
......
# @ohos.util.HashSet (Nonlinear Container HashSet)
> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
**HashSet** is implemented based on [HashMap](js-apis-hashmap.md). In **HashSet**, only the **value** object is processed.
Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted order, **HashSet** stores data in a random order. This means that **HashSet** may use a different order when storing and accessing elements. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**.
......@@ -12,6 +9,11 @@ Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted o
This topic uses the following to identify the use of generics:
- T: Type
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
......@@ -125,9 +127,8 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
```ts
let hashSet = new HashSet();
let result = hashSet.has("squirrel");
hashSet.add("squirrel");
let result1 = hashSet.has("squirrel");
let result = hashSet.has("squirrel");
```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册