提交 bd2357f1 编写于 作者: Y yuyaozhi 提交者: Gitee

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

......@@ -2,11 +2,7 @@
The ability assistant enables you to start applications, atomic services, and test cases and debug applications. By using this tool, you can send commands in the hdc shell to perform various system operations, such as starting abilities, forcibly stopping processes, and printing ability information.
## Development Guidelines
The ability assistant is pre-installed in the device environment. You can directly invoke the tool using commands.
### Query-related Commands
## Query-related Commands
- **help**
......@@ -22,7 +18,7 @@ The ability assistant is pre-installed in the device environment. You can direct
aa help
```
### Ability-related Commands
## Ability-related Commands
- **start**
......@@ -69,18 +65,18 @@ The ability assistant is pre-installed in the device environment. You can direct
- **dump**
Prints ability-related information.
Prints ability related information.
| Name | Level-2 Parameter | Description |
| ----------------- | -------------------- | ------------------------------------------------------------ |
| -h/--help | - | Prints help information. |
| -a/--all | - | Prints ability information in all missions. |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>NORMAL <br>DEFAULT_STANDARD<br>DEFAULT_SINGLE<br>LAUNCHER |
| -e/--extension | elementName | Prints extended component information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters.<br>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**|
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.|
| -d/--data | | Prints Data ability information. |
| -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. |
| -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters.<br>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**|
| -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.|
**Method**
......
# Ability Framework Overview
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more **Ability** instances.
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms.
- FA model, which applies to application development using API 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
| Item | FA Model | Stage Model |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The **config.json** file is used to describe the HAP and component information. The component must use a fixed file name.| The **module.json** file is used to describe the HAP and component information. The entry file name can be specified.|
| Intra-process object sharing| Not supported | Supported |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
In addition, the following differences exist in the development process:
......@@ -28,4 +28,7 @@ In addition, the following differences exist in the development process:
![lifecycle](figures/lifecycle.png)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
\ No newline at end of file
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
......@@ -3,22 +3,15 @@
## Overall Architecture
The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling.
The Feature Ability (FA) model applies to application development using API 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities.
The Feature Ability (FA) model applies to application development using API version 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities.
- The Page ability implements the ArkUI and provides the capability of interacting with users.
- The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke.
- The Data ability does not have a UI. It also runs in the background and enables other abilities to insert, delete, and query data.
- The Data ability does not have a UI. It runs in the background and enables other abilities to insert, delete, and query data.
- The Form ability provides a widget, which is a UI display mode.
## Application Package Structure
**The following figure shows the application package structure.**
![fa-package-info](figures/fa-package-info.png)
For details about the application package structure, see [Description of the Application Package Structure Configuration File](../quick-start/package-structure.md).
## Lifecycle
Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and is the interaction entry of applications.
Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users.
**The following figure shows the lifecycle of the Page ability.**
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
......@@ -30,6 +23,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
## Process and Thread Model
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. An application process is created when an ability is started for the first time, and a thread is created for this ability too. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. Therefore, abilities are isolated from each other.
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
......@@ -2,19 +2,18 @@
## When to Use
Ability continuation is to continue the current mission of an application, including the UI component status variables and distributed objects, on another device. The UI component status variables are used to synchronize page data, and the distributed objects are used to synchronize data in the memory.
Ability continuation is to continue the current mission of an application, including the UI component state variables and distributed objects, on another device. The UI component state variables are used to synchronize UI data, and the distributed objects are used to synchronize memory data.
## Available APIs
The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-application-ability.md).
The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 1** Ability continuation APIs
|API| Description|
|:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the **initiator** to save data during the ability continuation preparation process. The return value **0** means that the continuation request is accepted, and an error code means that the continuation request is denied.|
| onCreate(want: Want, param: LaunchParam): void| Called by the **target** to restore the data and page.|
| **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.|
| onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.|
......@@ -22,6 +21,8 @@ The following table lists the APIs used for ability continuation. For details ab
![continuation_dev](figures/continuation-info.png)
In effect, ability continuation is a cross-device ability startup that carries data. When the continuation is triggered, device A calls back **onContinue()** of the application. You must save the current data in this API. Then, device A initiates a cross-device ability startup on device B and transmits the data to device B. Device B calls back **onCreate()**. You must restore the transmitted data in this API.
## How to Develop
### Application Continuation
......@@ -31,78 +32,84 @@ The following table lists the APIs used for ability continuation. For details ab
- Configure the application to support ability continuation.
Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device.
```javascript
"continuable": true
```
```javascript
"continuable": true
```
* Configure the application startup type.
- Configure the application startup type.
Set **launchType** in the **module.json5** to **standard**. Currently, only multi-instance applications can be continued on another device.
```javascript
"launchType": "standard"
```
Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application.
```javascript
"launchType": "standard"
```
* Apply for the distributed permissions.
- Apply for the distributed permissions.
Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application.
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class:
```javascript
requestPermissions = async () => {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission = false
let accessManger = accessControl.createAtManager()
Logger.info("app permission get bundle info")
let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
for (const permission of permissions) {
Logger.info(`app permission query grant status ${permission}`)
try {
let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
if (grantStatus === PERMISSION_REJECT) {
needGrantPermission = true
break;
}
} catch (err) {
Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
needGrantPermission = true
break;
}
}
if (needGrantPermission) {
Logger.info("app permission needGrantPermission")
try {
await this.context.requestPermissionsFromUser(permissions)
} catch (err) {
Logger.error(`app permission ${JSON.stringify(err)}`)
}
} else {
Logger.info("app permission already granted")
}
}
```
2. Implement the **onContinue** API.
The **onContinue** API is called by the **initiator** to save the UI component status variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE** to accept the continuation request. If an error code is returned, the request is denied. If this API is not implemented, the system rejects the continuation request by default.
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class:
```javascript
requestPermissions = async () => {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission = false
let accessManger = accessControl.createAtManager()
Logger.info("app permission get bundle info")
let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
for (const permission of permissions) {
Logger.info(`app permission query grant status ${permission}`)
try {
let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
if (grantStatus === PERMISSION_REJECT) {
needGrantPermission = true
break;
}
} catch (err) {
Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
needGrantPermission = true
break;
}
}
if (needGrantPermission) {
Logger.info("app permission needGrantPermission")
try {
await this.context.requestPermissionsFromUser(permissions)
} catch (err) {
Logger.error(`app permission ${JSON.stringify(err)}`)
}
} else {
Logger.info("app permission already granted")
}
}
```
2. Implement the **onContinue()** API.
The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE(0)** to accept the continuation request. If an error code is returned, the request is rejected. If this API is not implemented, the system rejects the continuation request by default.
Modules to import:
......@@ -111,41 +118,38 @@ The following table lists the APIs used for ability continuation. For details ab
import AbilityConstant from '@ohos.application.AbilityConstant';
```
- To implement ability continuation, you must implement this API and have the value **AGREE** returned.
- Example
To implement ability continuation, you must implement this API and have the value **AGREE** returned.
Example
```javascript
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
// Set the user input data into the want parameter.
wantParam["input"] = AppStorage.Get<string>('ContinueInput');
Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE
}
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
// Set the user input data into want params.
wantParam["input"] = AppStorage.Get<string>('ContinueInput');
Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE
}
```
3. Implement the continuation logic in the **onCreate()** API.
The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored.
3. Implement the continuation logic in the **onCreate** API.
The **onCreate** API is called by the **target**. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component status, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored.
- The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**.
- After data restore is complete, call **restoreWindowStage** to trigger page restoration.
* Example
The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**.
After data restore is complete, call **restoreWindowStage** to trigger page restoration.
Example
```javascript
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
let input = want.parameters.input // get user data from want params
let input = want.parameters.input // Obtain user data from want params.
AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
......@@ -159,71 +163,68 @@ The following table lists the APIs used for ability continuation. For details ab
### Data Continuation
1. Use distributed objects.
Distributed data objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/database/database-distributedobject-guidelines.md).
In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device.
- In **onContinue**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**.
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
this.sessionId = distributedObject.genSessionId();
// Set the session ID for the distributed data object.
g_object.setSessionId(this.sessionId);
g_object.name = "Amy";
// Set the session ID into the want parameter.
wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE
}
```
- The target device obtains the session ID from **onCreate**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated for correct data retrieval.
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
statusCallback(sessionId, networkid, status) {
Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
}
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
// Obtain the session ID of the distributed data object from the want parameter.
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
g_object.on("status", this.statusCallback);
// Set the session ID for data synchronization.
g_object.setSessionId(this.sessionId);
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
Use distributed objects.
Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](../database/database-distributedobject-guidelines.md).
In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device.
- In **onContinue()**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**.
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
this.sessionId = distributedObject.genSessionId();
// Set the session ID for the distributed data object.
g_object.setSessionId(this.sessionId);
g_object.name = "Amy";
// Set the session ID into the want parameter.
wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE
}
```
For details about the complete example, see the sample.
```
- The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated.
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
statusCallback(sessionId, networkid, status) {
Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
}
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
// Obtain the session ID of the distributed data object from the want parameter.
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
g_object.on("status", this.statusCallback);
// Set the session ID for data synchronization.
g_object.setSessionId(this.sessionId);
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
}
```
# Stage Model Overview
### Design Ideas
## Design Ideas
The stage model is designed to make it easier to develop complex applications in the distributed environment.
......@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model.
![stagedesign](figures/stagedesign.png)
The stage model is designed based on the following considerations:
The stage model is designed based on the following considerations:
- **Balance between application capabilities and overall system power consumption**
......@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations:
- **Support for multiple device types and window forms**
To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency of the component manager and window manager.
To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency for the component manager and window manager.
### Basic Concepts
## Basic Concepts
The following figure shows the basic concepts in the stage model.
......@@ -33,24 +33,24 @@ The following figure shows the basic concepts in the stage model.
- **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application.
- **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime.
- **Application**: runtime class of a bundle, which is invisible to developers in the runtime.
- **Context**: provides various capabilities that can be invoked by developers during the runtime. The **Ability** and **ExtensionAbility** classes have their own context classes, which inherit the base class **Context**. The base class provides information such as the bundle name, module name, and path.
- **Ability**: provides lifecycle callback, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **Context**: base class that the context classes of **Ability** and **ExtensionAbility** classes inherit. This class provides various capabilities that can be invoked by developers in the runtime, and various information such as the bundle name, module name, and path.
- **Ability**: class that provides lifecycle callbacks, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**.
- **WindowStage**: local window manager.
- **Window**: basic unit managed by the window manager. It has an ArkUI engine instance.
- **ArkUI Page**: displays declarative ArkUI.
- **ArkUI Page**: ArkUI development framework page.
### Lifecycle
## Lifecycle
The ability and ability stage lifecycles are the most important concepts in the basic process of an application. The comparison between the FA model lifecycle and stage model lifecycle is provided in [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage.
The ability and ability stage lifecycles are the rudiments of the basic process of an application. For details about how these lifecycles differ from those in the FA model, see [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage.
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
To implement multi-device-form tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes.
To implement device-specific tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes.
### Ability Instances and Missions
## Ability Instances and Missions
Abilities can be started in any of the following modes:
......@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes:
Each ability instance corresponds to a mission in **Launcher Recent**.
The mission corresponding to each ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space exceeds the upper limit.
The mission corresponding to an ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space reaches the upper limit.
![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png)
### ExtensionAbility Mechanism
## ExtensionAbility Mechanism
Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features:
......@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro
![ExtensionAbility](figures/ExtensionAbility.png)
### Process Model
## Process Model
All OpenHarmony applications are designed to meet the single-process model. In the single-process model, an application is not allowed to configure multiple processes, and all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes:
All OpenHarmony applications are designed to meet the single-process model. In the single-process model, all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes:
- Main process: runs all ability components, pages, and service logic.
......
......@@ -133,13 +133,13 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
```
// Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
samgr->AddSystemAbility(said, new TestAbility());
samgr->AddSystemAbility(saId, new TestAbility());
// Register the TestAbilityStub instance with the SystemAbilityManager on a different device.
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ISystemAbilityManager::SAExtraProp saExtra;
saExtra.isDistributed = true; // Set a distributed SA.
int result = samgr->AddSystemAbility(said, new TestAbility(), saExtra);
int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
```
6. Obtain the SA.
......@@ -149,12 +149,12 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
```
// Obtain the proxy of the SA registered on the local device.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(said);
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type.
// Obtain the proxies of the SAs registered with other devices.
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device.
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device.
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
```
......
......@@ -12,22 +12,29 @@ Currently you can have access to statistics on the application usage, and notifi
3. Upon start of a new day
- **The application usage statistics can include the following**:
1. Events of all applications based on the specified start time and end time
1. Events of all applications based on the specified start time and end time
2. Application usage duration statistics based on the specified start time and end time
3. Events of the current application based on the specified start time and end time
4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually)
5. Priority group of the current invoker application
6. Whether a specific application is in the idle state
7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used.
8. Number of notifications from applications based on the specified start time and end time
9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time
9. Priority group of the invoker application or a specified application
2. Application usage duration statistics based on the specified start time and end time
- **The setters can be used to:**
3. Events of the current application based on the specified start time and end time
Set the group for the application specified by **bundleName**.
4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually)
- **The registration APIs can be used to:**
5. Priority group of the current invoker application
Register a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback.
6. Whether a specific application is in the idle state
- **The deregistration APIs can be used to:**
7. The number of FA usage records specified by **maxNum**, sorted by time (most recent first)
If **maxNum** is not specified, the default value **1000** will be used.
Deregister the callback for application group changes.
### Required Permissions
- The **queryBundleActiveStates**, **queryBundleStateInfos**, and **queryBundleStateInfoByInterval** APIs used for device usage statistics are system APIs. Before calling these APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission.
- This permission is not required for calling **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup**, and **isIdleState**, which are third-party APIs.
- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**.
- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**.
# Audio Overview<a name="EN-US_TOPIC_0000001147055469"></a>
# Audio Overview
You can use APIs provided by the audio module to implement audio-related features, including audio playback and volume management.
>![](../public_sys-resources/icon-note.gif) **NOTE**
>Due to permission issues, the above features are temporarily unavailable for the standard system.
## Basic Concepts
## Basic Concepts<a name="section296512102281"></a>
- **Sampling**
Sampling is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval.
- **Sampling**
- **Sampling rate**
Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
Sampling is a process to obtain discrete-time signals by extracting samples from analog signals in a continuous time domain at a specific interval.
- **Sampling rate**
Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
- **Channel**
Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
- **Audio frame**
Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
- **PCM**
Pulse code modulation \(PCM\) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
- **Channel**
Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
- **Audio frame**
Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
- **PCM**<br>
Pulse code modulation (PCM) is a method used to digitally represent sampled analog signals. It converts continuous-time analog signals into discrete-time digital signal samples.
......@@ -20,8 +20,6 @@ During application development, you are advised to use **on('stateChange')** to
To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
## How to Develop
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
......@@ -31,7 +29,7 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
......@@ -58,49 +56,49 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as
In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9).
```js
audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType);
console.info('InterruptForceType: ' + interruptEvent.forceType);
console.info('AInterruptHint: ' + interruptEvent.hintType);
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
switch (interruptEvent.hintType) {
// Force Pause: Action was taken by framework.
// Halt the write calls to avoid data loss.
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
isPlay = false;
break;
// Force Stop: Action was taken by framework.
// Halt the write calls to avoid data loss.
case audio.InterruptHint.INTERRUPT_HINT_STOP:
isPlay = false;
break;
// Force Duck: Action was taken by framework,
// just notifying the app that volume has been reduced.
case audio.InterruptHint.INTERRUPT_HINT_DUCK:
break;
// Force Unduck: Action was taken by framework,
// just notifying the app that volume has been restored.
case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
switch (interruptEvent.hintType) {
// Share Resume: Action is to be taken by App.
// Resume the force paused stream if required.
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
startRenderer();
break;
// Share Pause: Stream has been interrupted,
// It can choose to pause or play concurrently.
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
isPlay = false;
pauseRenderer();
break;
}
}
});
audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType);
console.info('InterruptForceType: ' + interruptEvent.forceType);
console.info('AInterruptHint: ' + interruptEvent.hintType);
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
switch (interruptEvent.hintType) {
// Force Pause: Action was taken by framework.
// Halt the write calls to avoid data loss.
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
isPlay = false;
break;
// Force Stop: Action was taken by framework.
// Halt the write calls to avoid data loss.
case audio.InterruptHint.INTERRUPT_HINT_STOP:
isPlay = false;
break;
// Force Duck: Action was taken by framework,
// just notifying the app that volume has been reduced.
case audio.InterruptHint.INTERRUPT_HINT_DUCK:
break;
// Force Unduck: Action was taken by framework,
// just notifying the app that volume has been restored.
case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
switch (interruptEvent.hintType) {
// Share Resume: Action is to be taken by App.
// Resume the force paused stream if required.
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
startRenderer();
break;
// Share Pause: Stream has been interrupted,
// It can choose to pause or play concurrently.
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
isPlay = false;
pauseRenderer();
break;
}
}
});
```
3. Use **start()** to start audio rendering.
......@@ -178,38 +176,38 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as
5. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
```js
async function pauseRenderer() {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) {
console.info('Renderer is not running');
return;
}
await audioRenderer.pause();
state = audioRenderer.state;
if (state == audio.AudioState.STATE_PAUSED) {
console.info('Renderer paused');
} else {
console.error('Renderer pause failed');
}
}
async function stopRenderer() {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) {
console.info('Renderer is not running or paused');
return;
}
await audioRenderer.stop();
async function pauseRenderer() {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) {
console.info('Renderer is not running');
return;
}
await audioRenderer.pause();
state = audioRenderer.state;
if (state == audio.AudioState.STATE_PAUSED) {
console.info('Renderer paused');
} else {
console.error('Renderer pause failed');
}
}
state = audioRenderer.state;
if (state == audio.AudioState.STATE_STOPPED) {
console.info('Renderer stopped');
} else {
console.error('Renderer stop failed');
}
async function stopRenderer() {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) {
console.info('Renderer is not running or paused');
return;
}
await audioRenderer.stop();
state = audioRenderer.state;
if (state == audio.AudioState.STATE_STOPPED) {
console.info('Renderer stopped');
} else {
console.error('Renderer stop failed');
}
}
```
......@@ -218,22 +216,20 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as
**AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete.
```js
async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released');
return;
}
await audioRenderer.release();
state = audioRenderer.state;
if (state == STATE_RELEASED) {
console.info('Renderer released');
} else {
console.info('Renderer release failed');
}
}
```
async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released');
return;
}
await audioRenderer.release();
state = audioRenderer.state;
if (state == STATE_RELEASED) {
console.info('Renderer released');
} else {
console.info('Renderer release failed');
}
}
```
......@@ -54,16 +54,16 @@ await cameraManager.getCameras((err, cameras) => {
cameraArray = cameras
})
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
}
// Create a camera input stream.
let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
}
// Create a camera input stream.
let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
console.log('Promise returned with the CameraInput instance');
cameraInput = input
})
......
......@@ -8,13 +8,11 @@ You can use video playback APIs to convert video data into visible signals, play
![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png)
**Figure 2** Layer 0 diagram of video playback
![en-us_image_video_player](figures/en-us_image_video_player.png)
Note: Video playback requires hardware capabilities such as display, audio, and codec.
*Note: Video playback requires hardware capabilities such as display, audio, and codec.*
1. A third-party application obtains a surface ID from the XComponent.
2. The third-party application transfers the surface ID to the VideoPlayer JS.
......@@ -43,9 +41,7 @@ The full video playback process includes creating an instance, setting the URL,
For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes).
For details about how to create an XComponent, see [XComponent](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md).
*Note: **setSurface** must be called after the URL is set but before **prepare** is called.
For details about how to create an XComponent, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md).
```js
import media from '@ohos.multimedia.media'
......@@ -120,7 +116,7 @@ export class VideoPlayerDemo {
console.info('pause success');
}, this.failureCallback).catch(this.catchCallback);
// Use a promise to obtain the video track information.
// Use a promise to obtain the video track information communication_dsoftbus.
let arrayDescription;
await videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
......
......@@ -123,7 +123,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -28,7 +28,7 @@
- **src &gt; main &gt; ets &gt; MainAbility &gt; app.ets**: ability lifecycle file.
- **src &gt; main &gt; resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files.
- **src &gt; main &gt; 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.
- **build-profile.json5**: current module information and build configuration options, including **buildOption target**.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.js**: application-level compilation and build task script.
......@@ -157,7 +157,7 @@
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -109,7 +109,7 @@ Open the index.visual file, right-click the existing template components on the
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -27,7 +27,7 @@
- **src &gt; main &gt; js &gt; MainAbility &gt; app.js**: ability lifecycle file.
- **src &gt; main &gt; resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files.
- **src &gt; main &gt; 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.
- **build-profile.json5**: current module information and build configuration options, including **buildOption target**.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.js**: application-level compilation and build task script.
......@@ -168,7 +168,7 @@
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
# DataUriUtils Module
> **NOTE**<br/>
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......
......@@ -78,7 +78,7 @@ Starts an ability. This API uses a callback to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.|
| options | StartOptions | Yes| Parameters used for starting the ability.|
| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -111,7 +111,7 @@ Starts an ability. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.|
| options | StartOptions | No| Parameters used for starting the ability.|
| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.|
**Return value**
......@@ -180,7 +180,7 @@ Starts an ability. This API uses a callback to return the result when the abilit
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.|
| options | StartOptions | Yes| Parameters used for starting the ability.|
| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback&lt;[AbilityResult](js-apis-featureAbility.md#abilityresult)&gt; | Yes| Callback used to return the result.|
......@@ -213,7 +213,7 @@ Starts an ability. This API uses a promise to return the result when the ability
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.|
| options | StartOptions | No| Parameters used for starting the ability.|
| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.|
**Return value**
......
# ErrorCode
> **NOTE**<br>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -17,9 +16,9 @@ Defines the error code used when the ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| NO_ERROR | 0 | No error occurs. |
| INVALID_PARAMETER | -1 | Invalid parameter. |
| ABILITY_NOT_FOUND | -2 | The ability is not found. |
| PERMISSION_DENY | -3 | Permission denied. |
| NO_ERROR | 0 | No error occurs. |
| INVALID_PARAMETER | -1 | Invalid parameter.|
| ABILITY_NOT_FOUND | -2 | The ability is not found.|
| PERMISSION_DENY | -3 | Permission denied. |
# wantConstant
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import wantConstant from '@ohos.ability.wantConstant'
```
## wantConstant.Action
**System capability**: SystemCapability.Ability.AbilityBase
......@@ -20,32 +18,32 @@ Lists the permissions.
| Common Event Macro | Common Event Name | Subscriber Permission |
| ------------ | ------------------ | ---------------------- |
| ACTION_HOME | ohos.want.action.home | None |
| ACTION_DIAL | ohos.want.action.dial | None |
| ACTION_SEARCH | ohos.want.action.search | None |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | None |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None |
| ACTION_SEND_SMS | ohos.want.action.sendSms | None |
| ACTION_CHOOSE | ohos.want.action.choose | None |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | None |
| ACTION_VIDEO_CAPTUR<sup>8+</sup> | ohos.want.action.videoCapture | None |
| ACTION_SELECT | ohos.want.action.select | None |
| ACTION_SEND_DATA | ohos.want.action.sendData | None |
| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None |
| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None |
| ACTION_VIEW_DATA | ohos.want.action.viewData | None |
| ACTION_EDIT_DATA | ohos.want.action.editData | None |
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | None |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | None |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | None |
| ACTION_HOME | ohos.want.action.home | None |
| ACTION_DIAL | ohos.want.action.dial | None |
| ACTION_SEARCH | ohos.want.action.search | None |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | None |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None |
| ACTION_SEND_SMS | ohos.want.action.sendSms | None |
| ACTION_CHOOSE | ohos.want.action.choose | None |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | None |
| ACTION_VIDEO_CAPTUR<sup>8+</sup> | ohos.want.action.videoCapture | None |
| ACTION_SELECT | ohos.want.action.select | None |
| ACTION_SEND_DATA | ohos.want.action.sendData | None |
| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None |
| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None |
| ACTION_VIEW_DATA | ohos.want.action.viewData | None |
| ACTION_EDIT_DATA | ohos.want.action.editData | None |
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | None |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | None |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | None |
## wantConstant.Entity
......@@ -56,12 +54,12 @@ Lists the permissions.
| Common Event Macro | Common Event Name | Subscriber Permission |
| ------------ | ------------------ | ---------------------- |
| ENTITY_DEFAULT | entity.system.default | None |
| ENTITY_HOME | entity.system.homel | None |
| ENTITY_VOICE | ENTITY_VOICE | None |
| ENTITY_BROWSABLE | entity.system.browsable | None |
| ENTITY_VIDEO | entity.system.video | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
| ENTITY_DEFAULT | entity.system.default | None |
| ENTITY_HOME | entity.system.homel | None |
| ENTITY_VOICE | ENTITY_VOICE | None |
| ENTITY_BROWSABLE | entity.system.browsable | None |
| ENTITY_VIDEO | entity.system.video | None |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None |
## flags
......@@ -70,19 +68,19 @@ Lists the permissions.
| Name | Value | Description |
| ------------------------------------ | ---------- | ------------------------------------------------------------ |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. |
| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. |
| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. |
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler.|
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**. |
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists. |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. |
| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. |
| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. |
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.|
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.|
# Ability Access Control
# Ability Access Control
> **NOTE**<br/>
Provides program permission management capabilities, including authentication, authorization, and revocation.
> **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
......@@ -96,14 +99,12 @@ Grants a user granted permission to an application. This API uses a promise to r
var AtManager = abilityAccessCtrl.createAtManager();
let tokenID = 0;
let permissionFlag = 1;
let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag);
let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag);
promise.then(data => {
console.log(`promise: data->${JSON.stringify(data)}`);
});
```
### grantUserGrantedPermission
grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback&lt;number&gt;): void
......@@ -129,8 +130,12 @@ Grants a user granted permission to an application. This API uses an asynchronou
var AtManager = abilityAccessCtrl.createAtManager();
let tokenID = 0;
let permissionFlag = 1;
AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => {
console.log(`callback: data->${JSON.stringify(data)}`);
AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => {
if (err) {
console.log(`callback: err->${JSON.stringify(err)}`);
} else {
console.log(`callback: data->${JSON.stringify(data)}`);
}
});
```
......@@ -195,8 +200,12 @@ Revokes a user granted permission given to an application. This API uses an asyn
var AtManager = abilityAccessCtrl.createAtManager();
let tokenID = 0;
let permissionFlag = 1;
AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => {
console.log(`callback: data->${JSON.stringify(data)}`);
AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => {
if (err) {
console.log(`callback: err->${JSON.stringify(err)}`);
} else {
console.log(`callback: data->${JSON.stringify(data)}`);
}
});
```
......
# AbilityDelegatorRegistry
> **NOTE**<br>
> **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
......@@ -9,21 +10,19 @@
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
```
## AbilityLifecycleState
Enumerates the ability lifecycle states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------- | ---- | --------------------------- |
| UNINITIALIZED | 0 | The ability is in an invalid state. |
| CREATE | 1 | The ability is created. |
| FOREGROUND | 2 | The ability is running in the foreground. |
| BACKGROUND | 3 | The ability is running in the background. |
| DESTROY | 4 | The ability is destroyed. |
| Name | Value | Description |
| ------------- | ---- | --------------------------- |
| UNINITIALIZED | 0 | The ability is in an invalid state. |
| CREATE | 1 | The ability is created.|
| FOREGROUND | 2 | The ability is running in the foreground. |
| BACKGROUND | 3 | The ability is running in the background. |
| DESTROY | 4 | The ability is destroyed.|
......@@ -37,9 +36,9 @@ Obtains the **AbilityDelegator** object of the application.
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework. |
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.|
**Example**
......@@ -61,9 +60,9 @@ Obtains the **AbilityDelegatorArgs** object of the application.
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters. |
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.|
**Example**
......
# AbilityRunningInfo
> **NOTE**<br>
> **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.
Provides ability running information.
## Modules to Import
......@@ -11,13 +11,11 @@ Provides ability running information.
```js
import abilitymanager from '@ohos.application.abilityManager';
```
## Usage
## Usage
The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**.
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
......
# AbilityStageContext
> **NOTE**<br>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md).
......@@ -14,11 +15,8 @@ import AbilityStage from '@ohos.application.AbilityStage';
## Usage
The ability stage context is obtained through an **AbilityStage** instance.
```js
import AbilityStage from '@ohos.application.AbilityStage';
class MyAbilityStage extends AbilityStage {
......@@ -28,7 +26,6 @@ class MyAbilityStage extends AbilityStage {
}
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
# StartOptions
> **NOTE**<br>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
**StartOptions** is the basic communication component of the system.
## Modules to Import
```
import StartOptions from '@ohos.application.StartOptions';
```
......@@ -18,8 +17,8 @@ import StartOptions from '@ohos.application.StartOptions';
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name | Readable | Writable | Type | Mandatory | Description |
| Name| Readable| Writable| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | -------- |
| [windowMode](js-apis-window.md#windowmode) | Yes| No | number | No | Window mode. |
| displayId | Yes| No | number | No | Display ID. |
| [windowMode](js-apis-window.md#windowmode) | Yes| No| number | No| Window mode.|
| displayId | Yes| No| number | No| Display ID.|
# AbilityConstant
> **NOTE**<br>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Provides parameters related to ability launch.
## Modules to Import
```js
import AbilityConstant from '@ohos.application.AbilityConstant';
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable | Writable | Description |
| -------- | -------- | -------- | -------- | -------- |
| launchReason | LaunchReason | Yes | Yes | Ability launch reason. |
| lastExitReason | LastExitReason | Yes | Yes | Reason for the last exit. |
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| launchReason | LaunchReason| Yes| Yes| Ability launch reason.|
| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.|
## AbilityConstant.LaunchReason
......@@ -30,12 +28,12 @@ Enumerates ability launch reasons.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason. |
| START_ABILITY | 1 | Ability startup. |
| CALL | 2 | Call. |
| CONTINUATION | 3 | Ability continuation. |
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason.|
| START_ABILITY | 1 | Ability startup.|
| CALL | 2 | Call.|
| CONTINUATION | 3 | Ability continuation.|
## AbilityConstant.LastExitReason
......@@ -44,11 +42,11 @@ Enumerates reasons for the last exit.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason. |
| ABILITY_NOT_RESPONDING | 1 | The ability does not respond. |
| NORMAL | 2 | Normal status. |
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason.|
| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.|
| NORMAL | 2 | Normal status.|
## AbilityConstant.OnContinueResult
......@@ -57,8 +55,8 @@ Enumerates ability continuation results.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| AGREE | 0 | Continuation agreed. |
| REJECT | 1 | Continuation denied. |
| MISMATCH | 2 | Mismatch. |
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| AGREE | 0 | Continuation agreed.|
| REJECT | 1 | Continuation denied.|
| MISMATCH | 2 | Mismatch.|
# AbilityDelegator
> **NOTE**<br/>
>
> **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
......@@ -10,8 +10,6 @@
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
```
## AbilityDelegator
### addAbilityMonitor<sup>9+</sup>
......
# AbilityDelegatorArgs
> **NOTE**<br/>
>
> **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
......@@ -10,8 +10,6 @@
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
```
## AbilityDelegatorArgs
Describes the test parameters.
......
# AbilityLifecycleCallback
> **NOTE**<br>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
A callback class that provides APIs, such as **onAbilityCreate**, **onAbilityWindowStageCreate**, and **onAbilityWindowStageDestroy**, to listen for the lifecycle of the application context.
## Modules to Import
```js
import AbilityLifecycleCallback from "@ohos.application.abilityLifecycleCallback";
```
## AbilityLifecycleCallback.onAbilityCreate
......
# AbilityMonitor
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -10,8 +10,6 @@
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
```
## AbilityMonitor
Describes an ability monitor.
......
# AbilityStage
> **NOTE**<br/>
> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Runtime class for HAP files. It provides APIs to notify you when a HAP file starts loading. You can then initialize the HAP file, for example, pre-load resources and create threads.
## Modules to Import
```js
import AbilityStage from '@ohos.application.AbilityStage';
```
......@@ -22,8 +21,6 @@ Called when the application is created.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
```js
......
# MissionInfo
> **NOTE**<br>
> **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
......@@ -9,7 +10,6 @@
import MissionInfo from '@ohos.application.missionInfo'
```
## MissionInfo
Provides the mission information.
......
# ShellCmdResult
> **NOTE**<br>
>
> **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
......@@ -10,8 +10,6 @@
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
```
## ShellCmdResult
Describes the shell command execution result.
......
# StaticSubscriberExtensionAbility
> **NOTE**<br>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```
......@@ -20,9 +20,9 @@ Callback of the common event of a static subscriber.
**Parameters**
| Name | Type | Mandatory | Description |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | CommonEventData | Yes | Callback of the common event of a static subscriber. |
| event | CommonEventData | Yes| Callback of the common event of a static subscriber.|
**Example**
......
# appManager
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -25,9 +26,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example**
......@@ -49,9 +50,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example**
......@@ -75,9 +76,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example**
......@@ -99,9 +100,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example**
......@@ -122,9 +123,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.|
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.|
**Example**
......@@ -146,9 +147,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.|
**Example**
......
# Linear Container ArrayList
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **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.
When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is more efficient in random access but less efficient in the addition or removal operation, because its addition or removal operation affects the position of other elements in the container.
**Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read.
## Modules to Import
```ts
import ArrayList from '@ohos.util.ArrayList'
import ArrayList from '@ohos.util.ArrayList';
```
## System Capabilities
SystemCapability.Utils.Lang
## ArrayList
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of entries in an array list (called container later).|
| length | number | Yes| No| Number of elements in an array list (called container later).|
### constructor
......@@ -28,6 +35,8 @@ constructor()
A constructor used to create an **ArrayList** instance.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -39,19 +48,21 @@ let arrayList = new ArrayList();
add(element: T): boolean
Adds an entry at the end of this container.
Adds an element at the end of this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to add.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.|
**Example**
......@@ -69,14 +80,16 @@ Adds an entry at the end of this container.
insert(element: T, index: number): void
Inserts an entry at the specified position in this container.
Inserts an element at the specified position in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to insert.|
| index | number | Yes| Index of the position where the entry is to be inserted.|
| element | T | Yes| Target element.|
| index | number | Yes| Index of the position where the element is to be inserted.|
**Example**
......@@ -91,19 +104,21 @@ arrayList.insert(true, 2);
has(element: T): boolean
Checks whether this container has the specified entry.
Checks whether this container has the specified element.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to check.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.|
| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.|
**Example**
......@@ -118,19 +133,21 @@ let result1 = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf");
getIndexOf(element: T): number
Obtains the index of the first occurrence of the specified entry in this container.
Obtains the index of the first occurrence of the specified element in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to query.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.|
| number | Returns the position index if obtained; returns **-1** if the specified element is not found.|
**Example**
......@@ -150,19 +167,21 @@ let result = arrayList.getIndexOf(2);
getLastIndexOf(element: T): number
Obtains the index of the last occurrence of the specified entry in this container.
Obtains the index of the last occurrence of the specified element in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to query.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.|
| number | Returns the position index if obtained; returns **-1** if the specified element is not found.|
**Example**
......@@ -182,19 +201,21 @@ let result = arrayList.getLastIndexOf(2);
removeByIndex(index: number): T
Removes an entry with the specified position from this container.
Removes an element with the specified position from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| index | number | Yes| Position index of the entry to remove.|
| index | number | Yes| Position index of the target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| T | Entry removed.|
| T | Element removed.|
**Example**
......@@ -212,19 +233,21 @@ let result = arrayList.removeByIndex(2);
remove(element: T): boolean
Removes the first occurrence of the specified entry from this container.
Removes the first occurrence of the specified element from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to remove.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.|
**Example**
......@@ -241,7 +264,9 @@ let result = arrayList.remove(2);
removeByRange(fromIndex: number, toIndex: number): void
Removes from this container all of the entries within a range, including the entry at the start position but not that at the end position.
Removes from this container all of the elements within a range, including the element at the start position but not that at the end position.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
......@@ -268,7 +293,9 @@ arrayList.removeByRange(2, 6);
replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => T,
thisArg?: Object): void
Replaces all entries in this container with new entries, and returns the new ones.
Replaces all elements in this container with new elements, and returns the new ones.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
......@@ -281,8 +308,8 @@ callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Value of the entry that is currently traversed.|
| index | number | No| Position index of the entry that is currently traversed.|
| value | T | Yes| Value of the element that is currently traversed.|
| index | number | No| Position index of the element that is currently traversed.|
| arrlist | ArrayList&lt;T&gt; | No| Instance that invokes the **replaceAllElements** method.|
**Example**
......@@ -306,21 +333,23 @@ arrayList.replaceAllElements((value, index) => {
forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => void,
thisArg?: Object): void
Uses a callback to traverse the entries in this container and obtain their position indexes.
Uses a callback to traverse the elements in this container and obtain their position indexes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.|
| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.|
| thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Value of the entry that is currently traversed.|
| index | number | No| Position index of the entry that is currently traversed.|
| value | T | Yes| Value of the element that is currently traversed.|
| index | number | No| Position index of the element that is currently traversed.|
| arrlist | ArrayList&lt;T&gt; | No| Instance that invokes the **forEach** method.|
**Example**
......@@ -332,7 +361,7 @@ arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.forEach((value, index) => {
console.log(value, index);
console.log("value:" + value, index);
});
```
......@@ -340,7 +369,9 @@ arrayList.forEach((value, index) => {
sort(comparator?: (firstValue: T, secondValue: T) => number): void
Sorts entries in this container.
Sorts elements in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
......@@ -352,8 +383,8 @@ comparator
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| firstValue | T | Yes| Previous entry.|
| secondValue | T | Yes| Next entry.|
| firstValue | T | Yes| Previous element.|
| secondValue | T | Yes| Next element.|
**Example**
......@@ -363,8 +394,8 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.sort(a, (b => a - b));
arrayList.sort(a, (b => b - a));
arrayList.sort((a, b) => a - b);
arrayList.sort((a, b) => b - a);
arrayList.sort();
```
......@@ -372,7 +403,9 @@ arrayList.sort();
subArrayList(fromIndex: number, toIndex: number): ArrayList&lt;T&gt;
Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **ArrayList** instance.
Obtains elements within a range in this container, including the element at the start position but not that at the end position, and returns these elements as a new **ArrayList** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
......@@ -406,6 +439,8 @@ clear(): void
Clears this container and sets its length to **0**.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -423,6 +458,8 @@ clone(): ArrayList&lt;T&gt;
Clones this container and returns a copy. The modification to the copy does not affect the original instance.
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -447,6 +484,8 @@ getCapacity(): number
Obtains the capacity of this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -470,6 +509,8 @@ convertToArray(): Array&lt;T&gt;
Converts this container into an array.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -491,7 +532,9 @@ let result = arrayList.convertToArray();
isEmpty(): boolean
Checks whether this container is empty (contains no entry).
Checks whether this container is empty (contains no element).
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -516,6 +559,8 @@ increaseCapacityTo(newCapacity: number): void
Increases the capacity of this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -540,6 +585,8 @@ trimToCurrentLength(): void
Trims the capacity of this container to its current length.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -557,6 +604,8 @@ arrayList.trimToCurrentLength();
Obtains an iterator, each item of which is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -574,14 +623,14 @@ arrayList.add(4);
// Method 1:
for (let item of arrayList) {
console.log(item);
console.log("value:" + item);
}
// Method 2:
let iter = arrayList[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -1146,6 +1146,8 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt
Sets an audio parameter. This API uses an asynchronous callback to return the result.
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
......@@ -1159,7 +1161,7 @@ Sets an audio parameter. This API uses an asynchronous callback to return the re
**Example**
```
audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => {
audioManager.setAudioParameter('key_example', 'value_example', (err) => {
if (err) {
console.error('Failed to set the audio parameter. ${err.message}');
return;
......@@ -1174,6 +1176,8 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt;
Sets an audio parameter. This API uses a promise to return the result.
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
......@@ -1192,7 +1196,7 @@ Sets an audio parameter. This API uses a promise to return the result.
**Example**
```
audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => {
audioManager.setAudioParameter('key_example', 'value_example').then(() => {
console.log('Promise returned to indicate a successful setting of the audio parameter.');
});
```
......@@ -1203,6 +1207,8 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result.
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
......@@ -1215,7 +1221,7 @@ Obtains the value of an audio parameter. This API uses an asynchronous callback
**Example**
```
audioManager.getAudioParameter('PBits per sample', (err, value) => {
audioManager.getAudioParameter('key_example', (err, value) => {
if (err) {
console.error('Failed to obtain the value of the audio parameter. ${err.message}');
return;
......@@ -1230,6 +1236,8 @@ getAudioParameter(key: string): Promise&lt;string&gt;
Obtains the value of an audio parameter. This API uses a promise to return the result.
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
......@@ -1247,7 +1255,7 @@ Obtains the value of an audio parameter. This API uses a promise to return the r
**Example**
```
audioManager.getAudioParameter('PBits per sample').then((value) => {
audioManager.getAudioParameter('key_example').then((value) => {
console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value);
});
```
......
# Configuration
> **NOTE**<br>
> **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.
Provides the configuration for the environment where the ability is running.
## Modules to Import
```js
import Configuration from '@ohos.application.Configuration';
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type | Readable | Writable | Description |
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| language | string | Yes | Yes| Language of the application. |
| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes | Yes | Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.|
| direction<sup>9+</sup> | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**. |
| screenDensity<sup>9+</sup> | ScreenDensity | Yes| No | Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640). |
| displayId<sup>9+</sup> | number | Yes| No| ID of the display where the application is located. |
| language | string | Yes| Yes| Language of the application.|
| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.|
| direction<sup>9+</sup> | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.|
| screenDensity<sup>9+</sup> | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).|
| displayId<sup>9+</sup> | number | Yes| No| ID of the display where the application is located.|
# ConfigurationConstant
> **NOTE**<br>
> **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.
......@@ -27,11 +28,11 @@ ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Value | Description |
| Name| Value| Description|
| -------- | -------- | -------- |
| COLOR_MODE_NOT_SET | -1 | Unspecified color mode. |
| COLOR_MODE_DARK | 0 | Dark mode. |
| COLOR_MODE_LIGHT | 1 | Light mode. |
| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.|
| COLOR_MODE_DARK | 0 | Dark mode.|
| COLOR_MODE_LIGHT | 1 | Light mode.|
## ConfigurationConstant.Direction<sup>9+</sup>
......@@ -46,11 +47,11 @@ ConfigurationConstant.Direction.DIRECTION_VERTICAL
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Value | Description |
| Name| Value| Description|
| -------- | -------- | -------- |
| DIRECTION_NOT_SET | -1 | Unspecified direction. |
| DIRECTION_VERTICAL | 0 | Vertical direction. |
| DIRECTION_HORIZONTAL | 1 | Horizontal direction. |
| DIRECTION_NOT_SET | -1 | Unspecified direction.|
| DIRECTION_VERTICAL | 0 | Vertical direction.|
| DIRECTION_HORIZONTAL | 1 | Horizontal direction.|
## ConfigurationConstant.ScreenDensity<sup>9+</sup>
......@@ -65,12 +66,12 @@ ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_NOT_SET
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Value | Description |
| Name| Value| Description|
| -------- | -------- | -------- |
| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution. |
| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi. |
| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi. |
| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi. |
| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi. |
| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi. |
| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi. |
| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.|
| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.|
| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.|
| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.|
| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.|
| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.|
| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.|
# Linear Container Deque
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **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.
Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects:
**Queue** follows the principle of FIFO only and allows element removal at the front and insertion at the rear.
**Vector** supports insertion and deletion of elements in between, as well asat both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements.
**Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container.
## Modules to Import
```ts
import Deque from '@ohos.util.Deque'
import Deque from '@ohos.util.Deque';
```
## System Capabilities
SystemCapability.Utils.Lang
## Deque
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of entries in a double-ended queue (deque, called container later).|
| length | number | Yes| No| Number of elements in a deque (called container later).|
### constructor
......@@ -28,6 +34,8 @@ constructor()
A constructor used to create a **Deque** instance.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -38,13 +46,15 @@ let deque = new Deque();
insertFront(element: T): void
Inserts an entry at the front of this container.
Inserts an element at the front of this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to insert.|
| element | T | Yes| Target element.|
**Example**
......@@ -62,13 +72,15 @@ deque.insertFront(false);
insertEnd(element: T): void
Inserts an entry at the end of this container.
Inserts an element at the end of this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to insert.|
| element | T | Yes| Target element.|
**Example**
......@@ -86,19 +98,21 @@ deque.insertEnd(false);
has(element: T): boolean
Checks whether this container has the specified entry.
Checks whether this container has the specified element.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| element | T | Yes| Entry to check.|
| element | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.|
| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.|
**Example**
......@@ -113,13 +127,15 @@ let result1 = deque.has("Ahfbrgrbgnutfodgorrogorg");
popFirst(): T
Removes the first entry of this container.
Removes the first element of this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| T | Entry removed.|
| T | Element removed.|
**Example**
......@@ -137,13 +153,15 @@ let result = deque.popFirst();
popLast(): T
Removes the last entry of this container.
Removes the last element of this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| T | Entry removed.|
| T | Element removed.|
**Example**
......@@ -162,13 +180,15 @@ let result = deque.popLast();
forEach(callbackfn: (value: T, index?: number, deque?: Deque&lt;T&gt;) => void,
thisArg?: Object): void
Uses a callback to traverse the entries in this container and obtain their position indexes.
Uses a callback to traverse the elements in this container and obtain their position indexes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.|
| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.|
| thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn
......@@ -176,7 +196,7 @@ callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Value of the element that is currently traversed.|
| index | number | No| Position index of the entry that is currently traversed.|
| index | number | No| Position index of the element that is currently traversed.|
| deque | Deque&lt;T&gt; | No| Instance that invokes the **forEach** method.|
**Example**
......@@ -188,7 +208,7 @@ deque.insertEnd(4);
deque.insertFront(5);
deque.insertEnd(4);
deque.forEach((value, index) => {
console.log(value, index);
console.log("value:" + value, index);
});
```
......@@ -196,13 +216,15 @@ deque.forEach((value, index) => {
getFirst(): T
Obtains the first entry of this container.
Obtains the first element of this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| T | Entry obtained.|
| T | Element obtained.|
**Example**
......@@ -219,13 +241,15 @@ let result = deque.getFirst();
getLast(): T
Obtains the last entry of this container.
Obtains the last element of this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| T | Entry obtained.|
| T | Element obtained.|
**Example**
......@@ -242,9 +266,10 @@ let result = deque.getLast();
[Symbol.iterator]\(): IterableIterator&lt;T&gt;
Obtains an iterator, each item of which is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -261,14 +286,14 @@ deque.insertFront(4);
// Method 1:
for (let item of deque) {
console.log(item);
console.log("value:" + item);
}
// Method 2:
let iter = deque[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
# ExtensionContext
> **NOTE**<br/>
> 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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Implements the extension context. This module is inherited from **Context**.
......
# FormInfo
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Provides widget information.
......
# FormError
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Provides widget-related error codes.
......
# Geolocation
Location services provide basic functions such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -695,7 +696,7 @@ This is a system API and cannot be called by third-party applications.
disableLocation(callback: AsyncCallback&lt;boolean&gt;) : void;
Enables the location service. This API uses an asynchronous callback to return the result.
Disables the location service. This API uses an asynchronous callback to return the result.
This is a system API and cannot be called by third-party applications.
......@@ -722,7 +723,7 @@ This is a system API and cannot be called by third-party applications.
disableLocation() : Promise&lt;boolean&gt;
Enables the location service. This API uses a promise to return the result.
Disables the location service. This API uses a promise to return the result.
This is a system API and cannot be called by third-party applications.
......
# Nonlinear Container HashMap
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **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.
**HashMap** is a map implemented based on the array, linked list, and red-black tree. It provides efficient data query, insertion, and removal. The elements in a **HashMap** instance are mappings of key-value pairs. Each key must be unique and have only one value.
**HashMap** is faster in accessing data than **[TreeMap](js-apis-treemap.md)**, because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order.
**[HashSet](js-apis-hashset.md)** is implemented based on **HashMap**. The input parameter of **HashMap** consists of **key** and **value**. In **HashSet**, only the **value** object is processed.
**Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs.
## Modules to Import
```ts
import HashMap from '@ohos.util.HashMap'
import HashMap from '@ohos.util.HashMap';
```
## System Capabilities
SystemCapability.Utils.Lang
## HashMap
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of entries in a hash map (called container later).|
| length | number | Yes| No| Number of elements in a hash map (called container later).|
### constructor
......@@ -30,6 +35,8 @@ constructor()
A constructor used to create a **HashMap** instance.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -41,7 +48,9 @@ let hashMap = new HashMap();
isEmpty(): boolean
Checks whether this container is empty (contains no entry).
Checks whether this container is empty (contains no element).
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -63,11 +72,13 @@ hasKey(key: K): boolean
Checks whether this container contains the specified key.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key to check.|
| key | K | Yes| Target key.|
**Return value**
......@@ -91,11 +102,13 @@ hasValue(value: V): boolean
Checks whether this container contains the specified value.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | V | Yes| Value to check.|
| value | V | Yes| Target value.|
**Return value**
......@@ -119,11 +132,13 @@ get(key: K): V
Obtains the value of the specified key in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key to query.|
| key | K | Yes| Target key.|
**Return value**
......@@ -145,13 +160,15 @@ let result = hashMap.get("sdfs");
setAll(map: HashMap<K, V>): void
Adds all entries in a **HashMap** instance to this container.
Adds all elements in a **HashMap** instance to this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| map | HashMap<K, V> | Yes| **HashMap** instance whose entries are to be added to the current container.|
| map | HashMap<K, V> | Yes| **HashMap** instance whose elements are to be added to the current container.|
**Example**
......@@ -168,20 +185,22 @@ hashMap.setAll(newHashMap);
set(key: K, value: V): Object
Adds an entry to this container.
Adds an element to this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry to add.|
| value | V | Yes| Value of the entry to add.|
| key | K | Yes| Key of the target element.|
| value | V | Yes| Value of the element.|
**Return value**
| Type| Description|
| -------- | -------- |
| Object | Container that contains the new entry.|
| Object | Container that contains the new element.|
**Example**
......@@ -195,19 +214,21 @@ let result = hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123);
remove(key: K): V
Removes an entry with the specified key from this container.
Removes an element with the specified key from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry to remove.|
| key | K | Yes| Key of the target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| V | Value of the entry removed.|
| V | Value of the element.|
**Example**
......@@ -225,6 +246,8 @@ clear(): void
Clears this container and sets its length to **0**.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -239,7 +262,9 @@ hashMap.clear();
keys(): IterableIterator&lt;K&gt;
Obtains an iterator that contains all the entries in this container.
Obtains an iterator that contains all the elements in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -256,7 +281,7 @@ hashMap.set("sdfs", 356);
let iter = hashMap.keys();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -268,6 +293,8 @@ values(): IterableIterator&lt;V&gt;
Obtains an iterator that contains all the values in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -283,7 +310,7 @@ hashMap.set("sdfs", 356);
let iter = hashMap.values();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -293,20 +320,22 @@ while(temp != undefined) {
replace(key: K, newValue: V): boolean
Replaces an entry in this container.
Replaces an element in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry to replace.|
| newValue | V | Yes| New value of the entry.|
| key | K | Yes| Key of the target element.|
| newValue | V | Yes| New value of the element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is replaced successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is replaced successfully; returns **false** otherwise.|
**Example**
......@@ -321,20 +350,22 @@ let result = hashMap.replace("sdfs", 357);
forEach(callbackfn: (value?: V, key?: K, map?: HashMap<K, V>) => void, thisArg?: Object): void
Uses a callback to traverse the entries in this container and obtain their position indexes.
Uses a callback to traverse the elements in this container and obtain their position indexes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.|
| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.|
| thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | V | No| Value of the entry that is currently traversed.|
| key | K | No| Key of the entry that is currently traversed.|
| value | V | No| Value of the element that is currently traversed.|
| key | K | No| Key of the element that is currently traversed.|
| map | HashMap<K, V> | No| Instance that invokes the **forEach** method.|
**Example**
......@@ -344,7 +375,7 @@ let hashMap = new HashMap();
hashMap.set("sdfs", 123);
hashMap.set("dfsghsf", 357);
hashMap.forEach((value, key) => {
console.log(value, key);
console.log("value:" + value, key);
});
```
......@@ -353,7 +384,9 @@ hashMap.forEach((value, key) => {
entries(): IterableIterator&lt;[K, V]&gt;
Obtains an iterator that contains all the entries in this container.
Obtains an iterator that contains all the elements in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -370,8 +403,8 @@ hashMap.set("sdfs", 356);
let iter = hashMap.entries();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp[0]);
console.log(temp[1]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
```
......@@ -383,6 +416,8 @@ while(temp != undefined) {
Obtains an iterator, each item of which is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -397,16 +432,16 @@ hashMap.set("sdfs", 356);
// Method 1:
for (let item of hashMap) {
console.log("key: " + item[0]);
console.log("value: " + item[1]);
console.log("key:" + item[0]);
console.log("value:" + item[1]);
}
// Method 2:
let iter = hashMap[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp[0]);
console.log(temp[1]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
```
# Nonlinear Container HashSet
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **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**.
**Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set.
## Modules to Import
......@@ -10,18 +16,15 @@
import HashSet from '@ohos.util.HashSet';
```
## System Capabilities
SystemCapability.Utils.Lang
## HashSet
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of entries in a hash set (called container later).|
| length | number | Yes| No| Number of elements in a hash set (called container later).|
### constructor
......@@ -30,6 +33,8 @@ constructor()
A constructor used to create a **HashSet** instance.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -41,7 +46,9 @@ let hashSet = new HashSet();
isEmpty(): boolean
Checks whether this container is empty (contains no entry).
Checks whether this container is empty (contains no element).
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -61,19 +68,21 @@ let result = hashSet.isEmpty();
has(value: T): boolean
Checks whether this container contains the specified entry.
Checks whether this container contains the specified element.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Entry to check.|
| value | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the specified entry is contained; returns **false** otherwise.|
| boolean | Returns **true** if the specified element is contained; returns **false** otherwise.|
**Example**
......@@ -89,19 +98,21 @@ let result1 = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf");
add(value: T): boolean
Adds an entry to this container.
Adds an element to this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Entry to add.|
| value | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is added successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.|
**Example**
......@@ -115,19 +126,21 @@ let result = hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf");
remove(value: T): boolean
Removes an entry from this container.
Removes an element from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | Yes| Entry to remove.|
| value | T | Yes| Target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.|
**Example**
......@@ -145,6 +158,8 @@ clear(): void
Clears this container and sets its length to **0**.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -161,6 +176,8 @@ values(): IterableIterator&lt;T&gt;
Obtains an iterator that contains all the values in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -176,7 +193,7 @@ hashSet.add("sdfs");
let iter = hashSet.values();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -186,20 +203,22 @@ while(temp != undefined) {
forEach(callbackfn: (value?: T, key?: T, set?: HashSet&lt;T&gt;) => void, thisArg?: Object): void
Uses a callback to traverse the entries in this container and obtain their position indexes.
Uses a callback to traverse the elements in this container and obtain their position indexes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.|
| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.|
| thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | No| Value of the entry that is currently traversed.|
| key | T | No| Key of the entry that is currently traversed (same as **value**).|
| value | T | No| Value of the element that is currently traversed.|
| key | T | No| Key of the element that is currently traversed (same as **value**).|
| set | HashSet&lt;T&gt; | No| Instance that invokes the **forEach** method.|
**Example**
......@@ -209,7 +228,7 @@ let hashSet = new HashSet();
hashSet.add("sdfs");
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf");
hashSet.forEach((value, key) => {
console.log(value, key);
console.log("value:" + value, key);
});
```
......@@ -217,7 +236,9 @@ hashSet.forEach((value, key) => {
### entries
entries(): IterableIterator<[T, T]>
Obtains an iterator that contains all the entries in this container.
Obtains an iterator that contains all the elements in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -234,8 +255,8 @@ hashSet.add("sdfs");
let iter = hashSet.entries();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp[0]);
console.log(temp[1]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
```
......@@ -247,6 +268,8 @@ while(temp != undefined) {
Obtains an iterator, each item of which is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -269,7 +292,7 @@ for (let item of hashSet) {
let iter = hashSet[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value: " + temp);
temp = iter.next().value;
}
```
# Nonlinear Container LightWeightMap
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **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.
**LightWeightMap** stores key-value (KV) pairs. Each key must be unique and have only one value.
**LightWeightMap** is based on generics and uses a lightweight structure. Keys in the map are searched using hash values, which are stored in an array.
Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, **LightWeightMap** occupies less memory.
**Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**.
## Modules to Import
```ts
import LightWeightMap from '@ohos.util.LightWeightMap'
import LightWeightMap from '@ohos.util.LightWeightMap';
```
## System Capabilities
SystemCapability.Utils.Lang
## LightWeightMap
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of entries in a lightweight map (called container later).|
| length | number | Yes| No| Number of elements in a lightweight map (called container later).|
### constructor
......@@ -30,6 +37,8 @@ constructor()
A constructor used to create a **LightWeightMap** instance.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -41,7 +50,9 @@ let lightWeightMap = new LightWeightMap();
isEmpty(): boolean
Checks whether this container is empty (contains no entry).
Checks whether this container is empty (contains no element).
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -61,7 +72,9 @@ let result = lightWeightMap.isEmpty();
hasAll(map: LightWeightMap<K, V>): boolean
Checks whether this container contains all entries of the specified **LightWeightMap** instance.
Checks whether this container contains all elements of the specified **LightWeightMap** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
......@@ -73,7 +86,7 @@ Checks whether this container contains all entries of the specified **LightWeigh
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if all the entries in the specified **LightWeightMap** instance are contained; returns **false** otherwise.|
| boolean | Returns **true** if all the elements in the specified **LightWeightMap** instance are contained; returns **false** otherwise.|
**Example**
......@@ -93,11 +106,13 @@ hasKey(key: K): boolean;
Checks whether this container contains the specified key.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key to check.|
| key | K | Yes| Target key.|
**Return value**
......@@ -122,11 +137,13 @@ hasValue(value: V): boolean
Checks whether this container contains the specified value.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | V | Yes| Value to check.|
| value | V | Yes| Target value.|
**Return value**
......@@ -150,11 +167,13 @@ increaseCapacityTo(minimumCapacity: number): void
Increases the capacity of this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| minimumCapacity | number | Yes| Minimum number of entries to accommodate in this container.|
| minimumCapacity | number | Yes| Minimum number of elements to accommodate in this container.|
**Example**
......@@ -170,11 +189,13 @@ get(key: K): V
Obtains the value of the specified key in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key to query.|
| key | K | Yes| Target key.|
**Return value**
......@@ -196,19 +217,21 @@ let result = lightWeightMap.get("sdfs");
getIndexOfKey(key: K): number
Obtains the index of the first occurrence of an entry with the specified key in this container.
Obtains the index of the first occurrence of an element with the specified key in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry.|
| key | K | Yes| Key of the element.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.|
| number | Returns the position index if obtained; returns **-1** otherwise.|
**Example**
......@@ -224,19 +247,21 @@ let result = lightWeightMap.getIndexOfKey("sdfs");
getIndexOfValue(value: V): number
Obtains the index of the first occurrence of an entry with the specified value in this container.
Obtains the index of the first occurrence of an element with the specified value in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | V | Yes| Value of the entry.|
| value | V | Yes| Key of the element.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the position index if obtained; returns **-1** if the specified entry is not found.|
| number | Returns the position index if obtained; returns **-1** otherwise.|
**Example**
......@@ -252,13 +277,15 @@ let result = lightWeightMap.getIndexOfValue(123);
getKeyAt(index: number): K
Obtains the key of an entry at the specified position in this container.
Obtains the key of an element at the specified position in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| index | number | Yes| Position index of the entry.|
| index | number | Yes| Position index of the element.|
**Return value**
......@@ -280,13 +307,15 @@ let result = lightWeightMap.getKeyAt(1);
setAll(map: LightWeightMap<K, V>): void
Adds all entries in a **LightWeightMap** instance to this container.
Adds all elements in a **LightWeightMap** instance to this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| map | LightWeightMap<K, V> | Yes| **LightWeightMap** instance whose entries are to be added to the current container.|
| map | LightWeightMap<K, V> | Yes| **LightWeightMap** instance whose elements are to be added to the current container.|
**Example**
......@@ -302,20 +331,22 @@ lightWeightMap.setAll(map);
### set
set(key: K, value: V): Object
Adds an entry to this container.
Adds an element to this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry to add.|
| value | V | Yes| Value of the entry to add.|
| key | K | Yes| Key of the target element.|
| value | V | Yes| Value of the target element.|
**Return value**
| Type| Description|
| -------- | -------- |
| Object | Container that contains the new entry.|
| Object | Container that contains the new element.|
**Example**
......@@ -329,19 +360,21 @@ let result = lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123);
remove(key: K): V
Removes an entry with the specified key from this container.
Removes an element with the specified key from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the entry to remove.|
| key | K | Yes| Target key.|
**Return value**
| Type| Description|
| -------- | -------- |
| V | Value of the entry removed.|
| V | Value of the element removed.|
**Example**
......@@ -357,19 +390,21 @@ lightWeightMap.remove("sdfs");
removeAt(index: number): boolean
Removes an entry at the specified position from this container.
Removes an element at the specified position from this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| index | number | Yes| Position index of the entry.|
| index | number | Yes| Position index of the element.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the entry is removed successfully; returns **false** otherwise.|
| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.|
**Example**
......@@ -385,14 +420,16 @@ let result = lightWeightMap.removeAt(1);
setValueAt(index: number, newValue: V): boolean
Sets a value for an entry at the specified position in this container.
Sets a value for an element at the specified position in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| index | number | Yes| Position index of the entry.|
| newValue | V | Yes| Value of the entry to set.|
| index | number | Yes| Position index of the target element.|
| newValue | V | Yes| Value of the target element to set.|
**Return value**
......@@ -414,13 +451,15 @@ lightWeightMap.setValueAt(1, 3546);
getValueAt(index: number): V
Obtains the value of an entry at the specified position in this container.
Obtains the value of an element at the specified position in this container.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| index | number | Yes| Position index of the entry.|
| index | number | Yes| Position index of the element.|
**Return value**
......@@ -444,6 +483,8 @@ clear(): void
Clears this container and sets its length to **0**.
**System capability**: SystemCapability.Utils.Lang
**Example**
```ts
......@@ -460,6 +501,8 @@ keys(): IterableIterator&lt;K&gt;
Obtains an iterator that contains all the keys in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -475,7 +518,7 @@ lightWeightMap.set("sdfs", 356);
let iter = lightWeightMap.keys();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -487,6 +530,8 @@ values(): IterableIterator&lt;V&gt;
Obtains an iterator that contains all the values in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -502,7 +547,7 @@ lightWeightMap.set("sdfs", 356);
let iter = lightWeightMap.values();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp);
console.log("value:" + temp);
temp = iter.next().value;
}
```
......@@ -512,20 +557,22 @@ while(temp != undefined) {
forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap<K, V>) => void, thisArg?: Object): void
Uses a callback to traverse the entries in this container and obtain their position indexes.
Uses a callback to traverse the elements in this container and obtain their position indexes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the entries in the container.|
| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.|
| thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | V | No| Value of the entry that is currently traversed.|
| key | K | No| Key of the entry that is currently traversed.|
| value | V | No| Value of the element that is currently traversed.|
| key | K | No| Key of the element that is currently traversed.|
| map | LightWeightMap<K, V> | No| Instance that invokes the **forEach** method.|
**Example**
......@@ -535,7 +582,7 @@ let lightWeightMap = new LightWeightMap();
lightWeightMap.set("sdfs", 123);
lightWeightMap.set("dfsghsf", 357);
lightWeightMap.forEach((value, key) => {
console.log(value, key);
console.log("value:" + value, key);
});
```
......@@ -544,7 +591,9 @@ lightWeightMap.forEach((value, key) => {
entries(): IterableIterator<[K, V]>
Obtains an iterator that contains all the entries in this container.
Obtains an iterator that contains all the elements in this container.
**System capability**: SystemCapability.Utils.Lang
**Return value**
......@@ -561,8 +610,8 @@ lightWeightMap.set("sdfs", 356);
let iter = lightWeightMap.entries();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp[0]);
console.log(temp[1]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
```
......@@ -571,13 +620,15 @@ while(temp != undefined) {
toString(): String
Concatenates the entries in this container into a string and returns the string.
Concatenates the elements in this container into a string and returns the string.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
| String | Returns a string.|
| Type| Description|
| -------- | -------- |
| String | String obtained.|
**Example**
......@@ -594,6 +645,8 @@ Concatenates the entries in this container into a string and returns the string.
Obtains an iterator, each item of which is a JavaScript object.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -609,16 +662,16 @@ lightWeightMap.set("sdfs", 356);
// Method 1:
for (let item of lightWeightMap) {
console.log("key: " + item[0]);
console.log("value: " + item[1]);
console.log("key:" + item[0]);
console.log("value:" + item[1]);
}
// Method 2:
let iter = lightWeightMap[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
console.log(temp[0]);
console.log(temp[1]);
console.log("key:" + temp[0]);
console.log("value:" + temp[1]);
temp = iter.next().value;
}
```
# Media
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources.
......
......@@ -635,7 +635,7 @@ Switches a given mission to the foreground, with the startup parameters for the
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| missionId | number | Yes| Mission ID.|
| options | StartOptions | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
| options | [StartOptions](js-apis-application-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.|
**Example**
......@@ -669,7 +669,7 @@ Switches a given mission to the foreground, with the startup parameters for the
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| missionId | number | Yes| Mission ID.|
| options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
| options | [StartOptions](js-apis-application-StartOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
**Return value**
......
# ParticleAbility Module
# ParticleAbility
> **NOTE**<br/>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the FA model.
## Constraints
......
# PermissionRequestResult
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Provides the permission request result.
......
......@@ -85,7 +85,7 @@ Uploads files. This API uses a promise to return the result.
```js
let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" };
let data = { name: "name123", value: "123" };
let header = { key1: value1, key2: value2 };
let header = { key1: "value1", key2: "value2" };
let uploadTask;
request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => {
uploadTask = data;
......@@ -117,7 +117,7 @@ Uploads files. This API uses an asynchronous callback to return the result.
```js
let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" };
let data = { name: "name123", value: "123" };
let header = { key1: value1, key2: value2 };
let header = { key1: "value1", key2: "value2" };
let uploadTask;
request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => {
if (err) {
......
# TestRunner
> **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.
> **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
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册