未验证 提交 a7d0c79f 编写于 作者: O openharmony_ci 提交者: Gitee

!13698 翻译完成:元能力Ability全量更新+删除多余的英文文档

Merge pull request !13698 from wusongqing/TR13383V2
# Geocoding and Reverse Geocoding Capabilities
## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs
The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table1** APIs for geocoding and reverse geocoding
| API | Description |
| -------- | -------- |
| isGeocoderAvailable(): boolean; | Checks whether the (reverse) geocoding service is available.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. |
## How to Develop
> **NOTE**
>
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```ts
import geoLocationManager from '@ohos.geolocation';
```
2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```ts
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```ts
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
# Obtaining Device Location Information
## When to Use
You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device.
Real-time location of the device is recommended for location-sensitive services. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device.
## Available APIs
For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.
The system provides the following location permissions:
- ohos.permission.LOCATION
- ohos.permission.APPROXIMATELY_LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking:
API versions earlier than 9: Apply for **ohos.permission.LOCATION**.
API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately.
| Target API Level| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- |
| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters|
| 9 and later| ohos.permission.LOCATION | Failure| No location obtained|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters|
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
```ts
import geoLocationManager from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
**Method 1:**
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
```
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
**Table 2** Common use cases of the location function
| Use Case | Constant | Description |
| ------------ | ------------------- | ------------------------------------------------------------ |
| Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for navigation:
```ts
var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
```ts
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
**Table 3** Location priority policies
| Policy | Constant | Description |
| ------------------ | -------------- | ------------------------------------------------------------ |
| Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```ts
var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic.
```ts
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start device location.
```ts
geoLocationManager.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```ts
geoLocationManager.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
# Location Overview
People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by , mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
## Basic Concepts
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
- **Coordinate**
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
- **GNSS positioning**
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
- **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
- **WLAN or Bluetooth positioning**
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
## Working Principles
Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location information to the application on a real-time basis.
## Limitations and Constraints
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
## Samples
The following sample is provided to help you better understand how to develop location services:
-[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location)
# @ohos.ability.ability
# @ohos.ability.ability (Ability)
The **Ability** module provides all level-2 module APIs for developers to export.
......
# @ohos.ability.dataUriUtils
# @ohos.ability.dataUriUtils (dataUriUtils)
The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module.
......
# @ohos.ability.errorCode
# @ohos.ability.errorCode (ErrorCode)
The **ErrorCode** module defines the error codes that can be used when the ability is started.
**NOTE**
The **ErrorCode** module defines the error codes that may be returned when an ability is started.
> **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
......@@ -14,13 +14,13 @@ import errorCode from '@ohos.ability.errorCode'
## ErrorCode
Defines the error codes used when the ability is started.
Enumerates the error codes that may be returned when an ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| NO_ERROR | 0 | No error occurs. |
| NO_ERROR | 0 | No error. |
| INVALID_PARAMETER | -1 | Invalid parameter.|
| ABILITY_NOT_FOUND | -2 | The ability is not found.|
| PERMISSION_DENY | -3 | Permission denied. |
# @ohos.ability.particleAbility
# @ohos.ability.particleAbility (ParticleAbility)
The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability.
The **particleAbility** module provides APIs for operating a ServiceAbility. You can use the APIs to start and terminate a ParticleAbility, obtain a **dataAbilityHelper** object, and connect to or disconnect from a ServiceAbility.
> **NOTE**
>
......@@ -21,7 +21,12 @@ import particleAbility from '@ohos.ability.particleAbility'
startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<void>): void
Starts a Particle ability. This API uses an asynchronous callback to return the result.
Starts a ParticleAbility. This API uses an asynchronous callback to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -48,7 +53,7 @@ particleAbility.startAbility(
flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
deviceId: "",
bundleName: "com.example.Data",
abilityName: "com.example.Data.MainAbility",
abilityName: "EntryAbility",
uri: ""
},
},
......@@ -62,7 +67,12 @@ particleAbility.startAbility(
startAbility(parameter: StartAbilityParameter): Promise\<void>;
Starts a Particle ability. This API uses a promise to return the result.
Starts a ParticleAbility. This API uses a promise to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -94,7 +104,7 @@ particleAbility.startAbility(
flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
deviceId: "",
bundleName: "com.example.Data",
abilityName: "com.example. Data.MainAbility",
abilityName: "EntryAbility",
uri: ""
},
},
......@@ -107,7 +117,7 @@ particleAbility.startAbility(
terminateSelf(callback: AsyncCallback\<void>): void
Terminates this Particle ability. This API uses an asynchronous callback to return the result.
Terminates this ParticleAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -133,7 +143,7 @@ particleAbility.terminateSelf(
terminateSelf(): Promise\<void>
Terminates this Particle ability. This API uses a promise to return the result.
Terminates this ParticleAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -161,6 +171,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper
Obtains a **dataAbilityHelper** object.
Observe the following when using this API:
- To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).
- If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Parameters**
......@@ -173,7 +189,7 @@ Obtains a **dataAbilityHelper** object.
| Type | Description |
| ----------------- | -------------------------------------------- |
| DataAbilityHelper | A utility class used to help other abilities access a Data ability.|
| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access a DataAbility.|
**Example**
......@@ -222,7 +238,7 @@ let wantAgentInfo = {
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
abilityName: "EntryAbility"
}
],
operationType: wantAgent.OperationType.START_ABILITY,
......@@ -283,7 +299,7 @@ let wantAgentInfo = {
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
abilityName: "EntryAbility"
}
],
operationType: wantAgent.OperationType.START_ABILITY,
......@@ -349,7 +365,7 @@ particleAbility.cancelBackgroundRunning(callback);
cancelBackgroundRunning(): Promise&lt;void&gt;;
Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1).
Requests to cancel a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1).
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
......@@ -376,7 +392,13 @@ particleAbility.cancelBackgroundRunning().then(() => {
connectAbility(request: Want, options:ConnectOptions): number
Connects this ability to a specific Service ability. This API uses a callback to return the result.
Connects this ability to a specific ServiceAbility.
Observe the following when using this API:
- To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**)..
- If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -384,23 +406,14 @@ Connects this ability to a specific Service ability. This API uses a callback to
| Name | Type | Mandatory| Description |
| ------- | -------------- | ---- | ---------------------------- |
| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.|
| options | ConnectOptions | Yes | Callback used to return the result. |
ConnectOptions
| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. |
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Mandatory | Description |
| ------------ | -------- | ---- | ------------------------- |
| onConnect | function | Yes | Callback invoked when the connection is successful. |
| onDisconnect | function | Yes | Callback invoked when the connection fails. |
| onFailed | function | Yes | Callback invoked when **connectAbility** fails to be called.|
**Example**
```ts
import particleAbility from '@ohos.ability.particleAbility'
import rpc from '@ohos.rpc'
function onConnectCallback(element, remote) {
......@@ -439,7 +452,7 @@ particleAbility.disconnectAbility(connId).then((data) => {
disconnectAbility(connection: number, callback:AsyncCallback\<void>): void;
Disconnects this ability from the Service ability. This API uses a callback to return the result.
Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -452,7 +465,8 @@ Disconnects this ability from the Service ability. This API uses a callback to r
**Example**
```ts
import rpc from '@ohos.rpc'
import particleAbility from '@ohos.ability.particleAbility';
import rpc from '@ohos.rpc';
function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
......@@ -489,7 +503,7 @@ var result = particleAbility.disconnectAbility(connId).then((data) => {
disconnectAbility(connection: number): Promise\<void>;
Disconnects this ability from the Service ability. This API uses a promise to return the result.
Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -502,7 +516,8 @@ Disconnects this ability from the Service ability. This API uses a promise to re
**Example**
```ts
import rpc from '@ohos.rpc'
import particleAbility from '@ohos.ability.particleAbility';
import rpc from '@ohos.rpc';
function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
......@@ -538,7 +553,7 @@ particleAbility.disconnectAbility(connId).then((data) => {
## ErrorCode
Enumerates error codes.
Enumerates the error codes.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......
# @ohos.ability.wantConstant
# @ohos.ability.wantConstant (wantConstant)
The **wantConstant** module provides the actions, entities, and flags used in **Want** objects.
......@@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant';
## wantConstant.Action
Enumerates the action constants of the **Want** object.
Enumerates the action constants of the **Want** object. **action** specifies the operation to execute.
**System capability**: SystemCapability.Ability.AbilityBase
......@@ -57,7 +57,7 @@ Enumerates the action constants of the **Want** object.
## wantConstant.Entity
Enumerates the entity constants of the **Want** object.
Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability.
**System capability**: SystemCapability.Ability.AbilityBase
......@@ -72,25 +72,25 @@ Enumerates the entity constants of the **Want** object.
## wantConstant.Flags
Describes flags.
Enumerates the flags that specify how the Want will be handled.
**System capability**: SystemCapability.Ability.AbilityBase
| 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 data to the URI. |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to 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.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| 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_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ServiceAbility is started regardless of whether the host application has been started. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| 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_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.|
# AccessibilityExtensionContext
The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities.
You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures.
> **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.
## Usage
Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**.
```js
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'
class MainAbility extends AccessibilityExtensionAbility {
onConnect(): void {
console.log("AxExtensionAbility onConnect");
let axContext = this.context;
}
}
```
## FocusDirection
Enumerates the focus directions.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| -------- | ------- |
| up | Search for the next focusable item above the current item in focus.|
| down | Search for the next focusable item below the current item in focus.|
| left | Search for the next focusable item on the left of the current item in focus.|
| right | Search for the next focusable item on the right of the current item in focus.|
| forward | Search for the next focusable item before the current item in focus.|
| backward | Search for the next focusable item after the current item in focus.|
## FocusType
Enumerates the focus types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| ------------- | ----------- |
| accessibility | Accessibility focus.|
| normal | Normal focus. |
## Rect
Defines a rectangle.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | --------- |
| left | number | Yes | No | Left boundary of the rectangle.|
| top | number | Yes | No | Top boundary of the rectangle.|
| width | number | Yes | No | Width of the rectangle. |
| height | number | Yes | No | Height of the rectangle. |
## WindowType
Enumerates the window types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| ----------- | --------- |
| application | Application window.|
| system | System window.|
## AccessibilityExtensionContext.setTargetBundleName
setTargetBundleName(targetNames: Array\<string>): Promise\<void>;
Sets the concerned target bundle.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------- | ---- | -------- |
| targetNames | Array&lt;string&gt; | Yes | Name of the target bundle.|
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```ts
this.context.setTargetBundleName(['com.ohos.mms']);
```
## AccessibilityExtensionContext.getFocusElement
getFocusElement(isAccessibilityFocus?: boolean): Promise\<AccessibilityElement>;
Obtains the focus element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------------------- | ------- | ---- | ------------------- |
| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.|
**Return value**
| Type | Description |
| ----------------------------------- | ---------------------- |
| Promise&lt;AccessibilityElement&gt; | Promise used to return the current focus element.|
**Example**
```ts
this.context.getFocusElement().then(focusElement => {
console.log("AxExtensionAbility getFocusElement success");
})
```
## AccessibilityExtensionContext.getWindowRootElement
getWindowRootElement(windowId?: number): Promise\<AccessibilityElement>;
Obtains the root element of a window.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | --------------------------- |
| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.|
**Return value**
| Type | Description |
| ----------------------------------- | ----------------------- |
| Promise&lt;AccessibilityElement&gt; | Promise used to return the root element.|
**Example**
```ts
this.context.getWindowRootElement().then(rootElement => {
console.log("AxExtensionAbility getWindowRootElement success");
})
```
## AccessibilityExtensionContext.getWindows
getWindows(displayId?: number): Promise<Array\<AccessibilityElement>>;
Obtains the list of windows visible to users.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------------------------- |
| displayId | number | No | Screen from which the window information is obtained. If this parameter is not specified, it indicates the default home screen.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;AccessibilityElement&gt;&gt; | Promise used to return the window list. |
**Example**
```ts
this.context.getWindows().then(windows => {
console.log("AxExtensionAbility getWindows success");
})
```
## AccessibilityExtensionContext.injectGesture
injectGesture(gesturePath: GesturePath, callback: AsyncCallback\<void>): void
Injects a gesture.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```ts
let gesturePath = new GesturePath(100);
for (let i = 0; i < 10; i++) {
let gesturePoint = new GesturePosition(100, i * 200);
gesturePath.positions.push(gesturePoint);
}
this.context.gestureInject(gesturePath, (result) => {
console.info('gestureInject result: ' + result);
})
```
## AccessibilityElement.attributeNames
attributeNames\<T extends keyof ElementAttributeValues>(): Promise\<Array\<T>>;
Obtains all attribute names of this element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;T&gt;&gt; | Promise used to return all attribute names of the element.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.attributeNames().then((values) => {
console.log("get attribute names success");
}).catch((err) => {
console.log("get attribute names err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.attributeValue
attributeValue\<T extends keyof ElementAttributeValues>(attributeName: T): Promise\<ElementAttributeValues[T]>;
Obtains the attribute value based on an attribute name.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| attributeName | T | Yes | Attribute name. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;ElementAttributeValues[T]&gt;&gt; | Promise used to return the attribute value.|
**Example**
```ts
let accessibilityElement;
try {
let attributeName = 'name';
accessibilityElement.attributeValue(attributeName).then((value) => {
console.log("get attribute value by name success");
}).catch((err) => {
console.log("get attribute value by name err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.actionNames
actionNames(): Promise\<Array\<string>>;
Obtains the names of all actions supported by this element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the names of all actions supported by the element.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.actionNames().then((values) => {
console.log("get action names success");
}).catch((err) => {
console.log("get action names err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.performAction
performAction(actionName: string, parameters?: object): Promise\<boolean>;
Performs an action based on the specified action name.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| actionName | string | Yes | Action name. |
| parameters | object | No | Parameter required for performing the target action. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;boolean&gt;&gt; | Promise used to return the result.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.performAction('action').then((result) => {
console.info('perform action result: ' + result);
}).catch((err) => {
console.log("perform action err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.findElement
findElement(type: 'content', condition: string): Promise\<Array\<AccessibilityElement>>;
Queries the information about this element based on the specified information type and condition.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| type | string | Yes | Information type. The value is fixed at **'content'**. |
| condition | string | Yes | Search criteria. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;T&gt;&gt; | Promise used to return the result.|
**Example**
```ts
let accessibilityElement;
try {
let condition = 'keyword';
accessibilityElement.findElement('content', condition).then((values) => {
console.log("find element success");
}).catch((err) => {
console.log("find element err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
# @ohos.app.ability.Ability
# @ohos.app.ability.Ability (Ability Base Class)
The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
This is the base class of [UIAbility](js-apis-app-ability-uiAbility.md) and [ExtensionAbility](js-apis-app-ability-extensionAbility.md). It provides the callbacks for system configuration updates and memory level updates. You cannot inherit from this base class.
> **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
```ts
import Ability from '@ohos.app.ability.Ability';
```
## Ability.onConfigurationUpdate
onConfigurationUpdate(newConfig: Configuration): void;
......@@ -23,40 +17,45 @@ Called when the configuration of the environment where the ability is running is
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.|
**Example**
```ts
class myAbility extends Ability {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example.
import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
```
## Ability.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
Called when the system adjusts the memory level.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.|
**Example**
```ts
class myAbility extends Ability {
// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example.
import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
}
```
# @ohos.app.ability.AbilityConstant
# @ohos.app.ability.AbilityConstant (AbilityConstant)
The **AbilityConstant** module provides ability launch parameters.
The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results.
The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes.
> **NOTE**
>
......@@ -17,31 +15,48 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
## Attributes
## AbilityConstant.LaunchParam
Defines the parameters for starting an ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Type| Readable| Writable| Description|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| launchReason | LaunchReason| Yes| Yes| Ability launch reason.|
| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.|
| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason, which is an enumerated type.|
| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit, which is an enumerated type.|
## AbilityConstant.LaunchReason
Enumerates the ability launch reasons.
Enumerates the initial ability launch reasons. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations.
**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.|
| APP_RECOVERY | 4 | Application recovery.|
| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-ability-context.md#abilitycontextstartability).|
| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall).|
| CONTINUATION | 3 | The ability is started by means of cross-device migration.|
| APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onCreate(want, launchParam) {
if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) {
console.log("The ability has been started by the way of startAbility.");
}
}
}
```
## AbilityConstant.LastExitReason
Enumerates reasons for the last exit.
Enumerates the reasons for the last exit. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -49,12 +64,25 @@ Enumerates reasons for the last exit.
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason.|
| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.|
| NORMAL | 2 | Normal status.|
| NORMAL | 2 | The ability exits normally.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onCreate(want, launchParam) {
if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) {
console.log("The ability has exit last because the ability was not responding.");
}
}
}
```
## AbilityConstant.OnContinueResult
Enumerates ability continuation results.
Enumerates the ability continuation results. You can use it together with [onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -64,9 +92,21 @@ Enumerates ability continuation results.
| REJECT | 1 | Continuation denied.|
| MISMATCH | 2 | Mismatch.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onContinue(wantParam) {
return AbilityConstant.OnConinueResult.AGREE;
}
}
```
## AbilityConstant.WindowMode
Enumerates the window modes in which an ability can be displayed at startup.
Enumerates the window modes in which an ability can be displayed at startup. It can be used in **startAbility()** to specify the window mode when the ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -78,36 +118,81 @@ Enumerates the window modes in which an ability can be displayed at startup.
| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
**Example**
```ts
let want = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
let option = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN
};
// Ensure that the context is obtained.
this.context.startAbility(want, option).then(()={
console.log("Succeed to start ability.");
}).catch((error)=>{
console.log("Failed to start ability with error: " + JSON.stringify(error));
});
```
## AbilityConstant.MemoryLevel
Enumerates the memory levels.
Enumerates the memory levels. You can use it in [onMemoryLevel(level)](js-apis-app-ability-ability.md#abilityonmemorylevel) of [Ability](js-apis-app-ability-ability.md) to complete different operations.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value| Description |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. |
| MEMORY_LEVEL_LOW | 1 | Low memory usage. |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage.|
| MEMORY_LEVEL_LOW | 1 | Low memory usage. |
| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. |
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onMemoryLevel(level) {
if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) {
console.log("The memory of device is critical, please release some memory.");
}
}
}
```
## AbilityConstant.OnSaveResult
Enumerates the result types for the operation of saving application data.
Enumerates the result types for the operation of saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| ALL_AGREE | 0 | Agreed to save the status.|
| ALL_AGREE | 0 | Always agreed to save the status.|
| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.|
| CONTINUATION_MISMATCH | 2 | Continuation mismatch.|
| RECOVERY_AGREE | 3 | Agreed to restore the saved status.|
| RECOVERY_REJECT | 4 | Rejected to restore the saved state.|
| ALL_REJECT | 5 | Rejected to save the status.|
| ALL_REJECT | 5 | Always rejected to save the status.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onSaveState(reason, wantParam) {
return AbilityConstant.OnSaveResult.ALL_AGREE;
}
}
```
## AbilityConstant.StateType
Enumerates the scenarios for saving application data.
Enumerates the scenarios for saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -115,3 +200,18 @@ Enumerates the scenarios for saving application data.
| ----------------------------- | ---- | ------------------------------------------------------------ |
| CONTINUATION | 0 | Saving the status in continuation.|
| APP_RECOVERY | 1 | Saving the status in application recovery.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onSaveState(reason, wantParam) {
if (reason === AbilityConstant.StateType.CONTINUATION) {
console.log("Save the ability data when the ability continuation.");
}
return AbilityConstant.OnSaveResult.ALL_AGREE;
}
}
```
# @ohos.app.ability.abilityDelegatorRegistry
# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)
The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application.
**AbilityDelegatorRegistry**, a module of the [Test Framework](../../ability-deprecated/ability-delegator.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters.
> **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 provided by this module can be used only in the test framework.
## Modules to Import
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## AbilityLifecycleState
Enumerates the ability lifecycle states.
Enumerates the ability lifecycle states. It can be used in [getAbilityState(ability)](js-apis-inner-application-abilityDelegator.md#getabilitystate9) of [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) to return different ability lifecycle states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------- | ---- | --------------------------- |
| UNINITIALIZED | 0 | The ability is in an invalid state. |
| 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. |
......@@ -30,7 +31,7 @@ Enumerates the ability lifecycle states.
getAbilityDelegator(): AbilityDelegator
Obtains the **AbilityDelegator** object of the application.
Obtains an [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) object.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -38,20 +39,33 @@ Obtains the **AbilityDelegator** object of the application.
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.|
| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule the functionalities of the test framework.|
**Example**
```ts
var abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let want = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
abilityDelegator.startAbility(want, (err) => {
if (err.code !== 0) {
console.log("Success start ability.");
} else {
console.log("Failed start ability, error: " + JSON.stringify(err));
}
})
```
## AbilityDelegatorRegistry.getArguments
getArguments(): AbilityDelegatorArgs
Obtains the **AbilityDelegatorArgs** object of the application.
Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -64,8 +78,11 @@ Obtains the **AbilityDelegatorArgs** object of the application.
**Example**
```ts
var args = AbilityDelegatorRegistry.getArguments();
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let args = AbilityDelegatorRegistry.getArguments();
console.info("getArguments bundleName:" + args.bundleName);
console.info("getArguments parameters:" + JSON.stringify(args.parameters));
console.info("getArguments testCaseNames:" + args.testCaseNames);
console.info("getArguments testRunnerClassName:" + args.testRunnerClassName);
```
# @ohos.app.ability.abilityLifecycleCallback
# @ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)
The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context.
The **AbilityLifecycleCallback** module defines the callbacks to receive lifecycle changes of [ApplicationContext](js-apis-inner-application-applicationContext.md). The callbacks include [onAbilityCreate](#abilitylifecyclecallbackonabilitycreate), [onWindowStageCreate](#abilitylifecyclecallbackonwindowstagecreate), [onWindowStageActive](#abilitylifecyclecallbackonwindowstageactive), [onWindowStageInactive](#abilitylifecyclecallbackonwindowstageinactive), [onWindowStageDestroy](#abilitylifecyclecallbackonwindowstagedestroy), [onAbilityDestroy](#abilitylifecyclecallbackonabilitydestroy), [onAbilityForeground](#abilitylifecyclecallbackonabilityforeground), [onAbilityBackground](#abilitylifecyclecallbackonabilitybackground), and [onAbilityContinue](#abilitylifecyclecallbackonabilitycontinue).
> **NOTE**
>
......@@ -25,10 +25,18 @@ Called when an ability is created.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate.");
}
};
```
## AbilityLifecycleCallback.onWindowStageCreate
......@@ -40,11 +48,19 @@ Called when the window stage of an ability is created.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate.");
}
};
```
## AbilityLifecycleCallback.onWindowStageActive
......@@ -56,11 +72,19 @@ Called when the window stage of an ability gains focus.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive.");
}
};
```
## AbilityLifecycleCallback.onWindowStageInactive
......@@ -72,11 +96,19 @@ Called when the window stage of an ability loses focus.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive.");
}
};
```
## AbilityLifecycleCallback.onWindowStageDestroy
......@@ -88,11 +120,19 @@ Called when the window stage of an ability is destroyed.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy.");
}
};
```
## AbilityLifecycleCallback.onAbilityDestroy
......@@ -104,10 +144,18 @@ Called when an ability is destroyed.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy.");
}
};
```
## AbilityLifecycleCallback.onAbilityForeground
......@@ -119,10 +167,18 @@ Called when an ability is switched from the background to the foreground.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground.");
}
};
```
## AbilityLifecycleCallback.onAbilityBackground
......@@ -134,10 +190,18 @@ Called when an ability is switched from the foreground to the background.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground.");
}
};
```
## AbilityLifecycleCallback.onAbilityContinue
......@@ -149,63 +213,91 @@ Called when an ability is continued on another device.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.|
**Example**
```ts
let abilityLifecycleCallback = {
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue.");
}
};
```
## Usage of AbilityLifecycleCallback
**Example**
```ts
import UIAbility from "@ohos.app.ability.UIAbility";
export default class MyAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
let AbilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
}
}
// 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext();
// 2. Use applicationContext to register a listener for the ability lifecycle in the application.
let lifecycleid = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
},
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
}
}
```
MyFirstAbility.ts
```ts
import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback";
import AbilityStage from "@ohos.app.ability.AbilityStage";
import UIAbility from '@ohos.app.ability.UIAbility';
// Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured.
let abilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate.");
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate.");
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive.");
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive.");
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy.");
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy.");
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground.");
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground.");
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue.");
}
};
export default class MyFirstAbility extends UIAbility {
onCreate() {
console.log("MyAbilityStage onCreate");
// 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext();
// 2. Register the listener for the ability lifecycle changes through the applicationContext object.
try {
globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId));
} catch (paramError) {
console.log("error: " + paramError.code + " ," + paramError.message);
}
}
}
```
MySecondAbility.ts
```ts
import UIAbility from "ohos.app.ability.UIAbility";
export default class MySecondAbility extends UIAbility {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
// 3. Deregister the listener for the environment changes through the applicationContext object.
applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => {
if (error.code != 0) {
console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error));
} else {
console.log("unregisterAbilityLifecycleCallback success.");
}
});
}
}
```
# @ohos.app.ability.abilityManager
# @ohos.app.ability.abilityManager (AbilityManager)
The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information.
The **AbilityManager** module provides APIs for obtaining, adding, and updating ability running information and state information.
> **NOTE**
>
......@@ -10,24 +10,24 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying
## Modules to Import
```ts
import AbilityManager from '@ohos.app.ability.abilityManager'
import abilityManager from '@ohos.app.ability.abilityManager';
```
## AbilityState
Enumerates the ability states.
Enumerates the ability states. This enum can be used together with [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) to return the ability state.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**System API**: This enum is an internal definition of a system API and cannot be called by third-party applications.
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
| FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the foregrounding state. |
| BACKGROUNDING | 12 | The ability is in the backgrounding state. |
| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. |
| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. |
## updateConfiguration
......@@ -43,25 +43,42 @@ Updates the configuration. This API uses an asynchronous callback to return the
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the API call result. You can perform error handling or custom processing in this callback. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
var config = {
language: 'chinese'
}
const config = {
language: 'Zh-Hans', // Simplified Chinese.
colorMode: COLOR_MODE_LIGHT, // Light theme.
direction: DIRECTION_VERTICAL, // Vertical direction.
screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI.
displayId: 1, // The application is displayed on the display with ID 1.
hasPointerDevice: true, // A pointer device is connected.
};
try {
abilitymanager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
abilityManager.updateConfiguration(config, (err) => {
if (err.code !== 0) {
console.log("updateConfiguration fail, err: " + JSON.stringify(err));
} else {
console.log("updateConfiguration success.");
}
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -79,32 +96,45 @@ Updates the configuration. This API uses a promise to return the result.
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.|
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise used to return the API call result. You can perform error handling or custom processing in this callback.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
var config = {
language: 'chinese'
}
const config = {
language: 'Zh-Hans', // Simplified Chinese.
colorMode: COLOR_MODE_LIGHT, // Light theme.
direction: DIRECTION_VERTICAL, // Vertical direction.
screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI.
displayId: 1, // The application is displayed on the display with ID 1.
hasPointerDevice: true, // A pointer device is connected.
};
try {
abilitymanager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
})
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success.');
}).catch((err) => {
console.log('updateConfiguration fail, err: ' + JSON.stringify(err));
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -122,20 +152,32 @@ Obtains the ability running information. This API uses an asynchronous callback
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | Yes | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
abilityManager.getAbilityRunningInfos((err, data) => {
if (err.code !== 0) {
console.log("getAbilityRunningInfos fail, error: " + JSON.stringify(err));
} else {
console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data));
}
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -153,22 +195,30 @@ Obtains the ability running information. This API uses a promise to return the r
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result.|
| Promise\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilitymanager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
abilityManager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err));
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -176,7 +226,7 @@ try {
getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
Obtains the extension running information. This API uses an asynchronous callback to return the result.
Obtains the ExtensionAbility running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -186,23 +236,35 @@ Obtains the extension running information. This API uses an asynchronous callbac
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 2<sup>31</sup>-1.|
| callback | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | Yes | Callback used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
var upperLimit = 0;
let upperLimit = 10;
try {
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => {
if (err.code !== 0) {
console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err));
} else {
console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data));
}
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -210,7 +272,7 @@ try {
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result.
Obtains the ExtensionAbility running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -220,30 +282,38 @@ Obtains the extension running information. This API uses a promise to return the
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 2<sup>31</sup>-1.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result.|
| Promise\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | Promise used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
var upperLimit = 0;
let upperLimit = 10;
try {
abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
})
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -259,21 +329,28 @@ Obtains the top ability, which is the ability that has the window focus. This AP
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<ElementName> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
try {
abilitymanager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
import abilityManager from '@ohos.app.ability.abilityManager';
abilityManager.getTopAbility((err, data) => {
if (err.code !== 0) {
console.log("getTopAbility fail, err: " + JSON.stringify(err));
} else {
console.log("getTopAbility success, data: " + JSON.stringify(data));
}
});
```
## getTopAbility
......@@ -288,21 +365,24 @@ Obtains the top ability, which is the ability that has the window focus. This AP
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<ElementName>| Promise used to return the result.|
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilitymanager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
abilityManager.getTopAbility().then((data) => {
console.log("getTopAbility success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility fail, err: " + JSON.stringify(err));
})
```
# @ohos.app.ability.AbilityStage
# @ohos.app.ability.AbilityStage (AbilityStage)
**AbilityStage** is a runtime class for HAP files.
......@@ -25,13 +25,15 @@ Called when the application is created.
**Example**
```ts
class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage.onCreate is called")
}
}
```
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage.onCreate is called");
}
}
```
## AbilityStage.onAcceptWant
......@@ -44,9 +46,9 @@ Called when a specified ability is started.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
**Return value**
......@@ -56,14 +58,16 @@ Called when a specified ability is started.
**Example**
```ts
class MyAbilityStage extends AbilityStage {
onAcceptWant(want) {
console.log("MyAbilityStage.onAcceptWant called");
return "com.example.test";
}
}
```
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage {
onAcceptWant(want) {
console.log("MyAbilityStage.onAcceptWant called");
return "com.example.test";
}
}
```
## AbilityStage.onConfigurationUpdate
......@@ -82,13 +86,15 @@ Called when the global configuration is updated.
**Example**
```ts
class MyAbilityStage extends AbilityStage {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, language:' + config.language);
}
}
```
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, language:' + config.language);
}
}
```
## AbilityStage.onMemoryLevel
......@@ -106,22 +112,24 @@ Called when the system has decided to adjust the memory level. For example, this
**Example**
```ts
class MyAbilityStage extends AbilityStage {
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
}
```
## AbilityStage.context
context: AbilityStageContext;
Describes the configuration information about the context.
Defines the context of **AbilityStage**.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Description |
| ----------- | --------------------------- | ------------------------------------------------------------ |
| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.|
| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | The context is obtained in the callback invoked when initialization is performed during ability startup.|
# @ohos.app.ability.appRecovery (Application Recovery)
# @ohos.app.ability.appRecovery (appRecovery)
The **appRecovery** module provides APIs for recovering failed applications.
The **appRecovery** module provides APIs for recovering faulty applications.
> **NOTE**
>
......@@ -8,13 +8,13 @@ The **appRecovery** module provides APIs for recovering failed applications.
## Modules to Import
```ts
import appRecovery from '@ohos.app.ability.appRecovery'
import appRecovery from '@ohos.app.ability.appRecovery';
```
## appRecovery.RestartFlag
Enumerates the application restart options used in [enableAppRecovery](#apprecoveryenableapprecovery).
Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -28,7 +28,7 @@ Enumerates the application restart options used in [enableAppRecovery](#apprecov
## appRecovery.SaveOccasionFlag
Enumerates the scenarios for saving the application state, which is used in [enableAppRecovery](#apprecoveryenableapprecovery).
Enumerates the scenarios for saving the application state. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -39,7 +39,7 @@ Enumerates the scenarios for saving the application state, which is used in [ena
## appRecovery.SaveModeFlag
Enumerates the application state saving modes used in [enableAppRecovery](#apprecoveryenableapprecovery).
Enumerates the application state saving modes. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -50,7 +50,7 @@ Enumerates the application state saving modes used in [enableAppRecovery](#appre
## appRecovery.enableAppRecovery
enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void;
enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void;
Enables application recovery.
......@@ -67,9 +67,17 @@ Enables application recovery.
**Example**
```ts
export default class MyAbilityStage extends AbilityStage {
import appRecovery from '@ohos.app.ability.appRecovery';
import AbilityStage from '@ohos.app.ability.AbilityStage';
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MyAbility extends UIAbility {
onCreate() {
appRecovery.enableAppRecovery(RestartFlag::ALWAYS_RESTART, SaveOccasionFlag::SAVE_WHEN_ERROR, SaveModeFlag::SAVE_WITH_FILE);
appRecovery.enableAppRecovery(
appRecovery.RestartFlag::ALWAYS_RESTART,
appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR,
appRecovery.SaveModeFlag::SAVE_WITH_FILE
);
}
}
```
......@@ -86,13 +94,21 @@ Restarts the application. This API can be used together with APIs of [errorManag
**Example**
```ts
var observer = {
import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager';
let observer = {
onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg)
appRecovery.restartApp();
}
}
};
try {
errorManager.on("error", observer);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appRecovery.saveAppState
......@@ -107,15 +123,24 @@ Saves the application state. This API can be used together with APIs of [errorMa
| Type| Description|
| -------- | -------- |
| boolean | Whether the saving is successful.|
| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.|
**Example**
```ts
var observer = {
import appRecovery from '@ohos.app.ability.appRecovery';
import errorManager from '@ohos.app.ability.errorManager';
let observer = {
onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg)
appRecovery.saveAppState();
}
};
try {
errorManager.on("error", observer);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
# @ohos.app.ability.common
# @ohos.app.ability.common (Context)
The **Common** module provides all level-2 module APIs for developers to export.
......@@ -15,21 +15,21 @@ import common from '@ohos.app.ability.common'
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No | Level-2 module **UIAbilityContext**. |
| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.|
| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.|
| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.|
| Context | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.|
| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.|
| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.|
| AreaMode | [AreaMode](#areamode) | No | Enumerated values of **AreaMode**.|
| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.|
| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.|
| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.|
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.|
| Name | Type | Description |
| ----------- | -------------------- | ------------------------------------------------------------ |
| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Level-2 module **UIAbilityContext**. |
| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Level-2 module **AbilityStageContext**.|
| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | Level-2 module **ApplicationContext**.|
| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | Level-2 module **BaseContext**.|
| Context | [Context](js-apis-inner-application-context.md) | Level-2 module **Context**.|
| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Level-2 module **ExtensionContext**.|
| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.|
| AreaMode | [AreaMode](#areamode) | Enumerated values of **AreaMode**.|
| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.|
| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | Level-2 module **PermissionRequestResult**.|
| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | Level-2 module **PacMap**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.|
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.|
**Example**
```ts
......@@ -52,11 +52,11 @@ let connectOptions: common.ConnectOptions;
## AreaMode
Defines the area where the file to be access is located. Each area has its own content.
Enumerates the data encryption levels.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| --------------- | ---- | --------------- |
| EL1 | 0 | Device-level encryption area. |
| EL2 | 1 | User credential encryption area. The default value is **EL2**.|
| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on. |
| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).|
# @ohos.app.ability.Configuration
# @ohos.app.ability.Configuration (Configuration)
The **Configuration** module defines environment change information.
......@@ -14,34 +14,42 @@ import Configuration from '@ohos.app.ability.Configuration'
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| language | string | Yes| Yes| Language of the application.|
| language | string | Yes| Yes| Language of the application, for example, **zh**.|
| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.|
| direction | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.|
| screenDensity | 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).|
| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.|
| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | 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 | number | Yes| No| ID of the display where the application is located.|
| hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.|
For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file.
**Example**
**Example**
```ts
let envCallback = {
onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`)
let language = config.language;
let colorMode = config.colorMode;
let direction = config.direction;
let screenDensity = config.screenDensity;
let displayId = config.displayId;
let hasPointerDevice = config.hasPointerDevice;
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let envCallback = {
onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`)
let language = config.language;
let colorMode = config.colorMode;
let direction = config.direction;
let screenDensity = config.screenDensity;
let displayId = config.displayId;
let hasPointerDevice = config.hasPointerDevice;
}
};
try {
let applicationContext = this.context.getApplicationContext();
let callbackId = applicationContext.on("environment", envCallback);
console.log("callbackId: " + callbackId);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
}
};
try {
var callbackId = applicationContext.on("environment", envCallback);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
# @ohos.app.ability.ConfigurationConstant
# @ohos.app.ability.ConfigurationConstant (ConfigurationConstant)
The **ConfigurationConstant** module provides the enumerated values of the environment configuration information.
......@@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| COLOR_MODE_LIGHT | 1 | Light mode.|
## ConfigurationConstant.Direction<sup>9+</sup>
## ConfigurationConstant.Direction
You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API.
......@@ -38,7 +38,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| DIRECTION_HORIZONTAL | 1 | Horizontal direction.|
## ConfigurationConstant.ScreenDensity<sup>9+</sup>
## ConfigurationConstant.ScreenDensity
You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API.
......
# @ohos.app.ability.contextConstant
# @ohos.app.ability.contextConstant (ContextConstant)
The **ContextConstant** module defines data encryption levels.
The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels.
> **NOTE**
>
......@@ -19,7 +19,7 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Value| Description|
| Name| Value| Description|
| -------- | -------- | -------- |
| EL1 | 0 | Device-level encryption area.|
| EL2 | 1 | User credential encryption area.|
| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.|
| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).|
# @ohos.app.ability.dataUriUtils
# @ohos.app.ability.dataUriUtils (DataUriUtils)
The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI.
......
# @ohos.app.ability.StartOptions
# @ohos.app.ability.StartOptions (StartOptions)
The **StartOptions** module implements ability startup options.
**StartOptions** is used as an input parameter of [startAbility()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) to specify the window mode of an ability.
> **NOTE**
>
......@@ -21,4 +21,4 @@ import StartOptions from '@ohos.app.ability.StartOptions';
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.|
| displayId | number | No| Display ID.|
| displayId | number | No| Display ID. The default value is **0**, indicating the current display.|
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册