未验证 提交 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.
......
......@@ -14,10 +14,10 @@ This module provides APIs for accessing ability-specific resources. You can use
Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**.
```ts
import Ability from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = undefined;
class MainAbility extends Ability {
let context = undefined;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context;
}
......@@ -30,8 +30,8 @@ class MainAbility extends Ability {
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| abilityInfo | AbilityInfo | Yes| No| Ability information.|
| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.|
| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.|
| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.|
| config | [Configuration](js-apis-application-configuration.md) | Yes| No| Configuration information.|
## AbilityContext.startAbility
......@@ -40,6 +40,11 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -54,13 +59,14 @@ Starts an ability. This API uses an asynchronous callback to return the result.
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
bundleName: "com.example.myapp",
bundleName: "com.example.myapplication",
abilityName: "MyAbility"
};
......@@ -89,6 +95,11 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
Starts an ability with the start options specified. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -104,15 +115,16 @@ Starts an ability with the start options specified. This API uses an asynchronou
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var options = {
windowMode: 0
......@@ -142,6 +154,11 @@ startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;
Starts an ability. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -162,13 +179,14 @@ Starts an ability. This API uses a promise to return the result.
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
bundleName: "com.example.myapp",
bundleName: "com.example.myapplication",
abilityName: "MyAbility"
};
var options = {
......@@ -198,7 +216,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void;
Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -214,15 +237,16 @@ Starts an ability. This API uses an asynchronous callback to return the result w
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -248,7 +272,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void;
Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated.
Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -265,15 +294,16 @@ Starts an ability with the start options specified. This API uses an asynchronou
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var options = {
windowMode: 0,
......@@ -303,7 +333,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;;
Starts an ability. This API uses a promise to return the result when the ability is terminated.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -326,13 +361,14 @@ Starts an ability. This API uses a promise to return the result when the ability
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
bundleName: "com.example.myapp",
bundleName: "com.example.myapplication",
abilityName: "MyAbility"
};
var options = {
......@@ -361,9 +397,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void;
Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed.
Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated.
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -375,22 +416,23 @@ Starts an ability. This API uses an asynchronous callback to return the result w
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<AbilityResult\> | Yes| Callback used to return the result.|
| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)\> | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -418,9 +460,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed.
Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated.
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -440,15 +487,16 @@ Starts an ability with the start options specified. This API uses an asynchronou
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -479,9 +527,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult\>;
Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed.
Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated.
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -499,22 +552,23 @@ Starts an ability with the start options specified. This API uses a promise to r
| Type| Description|
| -------- | -------- |
| Promise&lt;AbilityResult&gt; | Promise used to return the result.|
| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -543,7 +597,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability. This API uses an asynchronous callback to return the result.
Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -561,15 +615,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -594,7 +649,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startServiceExtensionAbility(want: Want): Promise\<void>;
Starts a new Service Extension ability. This API uses a promise to return the result.
Starts a ServiceExtensionAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -611,15 +666,16 @@ Starts a new Service Extension ability. This API uses a promise to return the re
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -644,9 +700,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result.
Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -665,15 +721,16 @@ Starts a new Service Extension ability with the account ID specified. This API u
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -699,9 +756,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result.
Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -719,15 +776,16 @@ Starts a new Service Extension ability with the account ID specified. This API u
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -752,7 +810,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -770,20 +828,27 @@ Stops a Service Extension ability in the same application. This API uses an asyn
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
this.context.startAbility(want, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbility(want, (error) => {
if (error.code) {
if (error.code != 0) {
// Process service logic errors.
console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
......@@ -803,7 +868,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
stopServiceExtensionAbility(want: Want): Promise\<void>;
Stops a Service Extension ability in the same application. This API uses a promise to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -820,18 +885,25 @@ Stops a Service Extension ability in the same application. This API uses a promi
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
this.context.startAbility(want, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbility(want)
.then((data) => {
// Carry out normal service processing.
......@@ -853,9 +925,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -874,19 +946,26 @@ Stops a Service Extension ability in the same application with the account ID sp
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
try {
this.context.startAbilityWithAccount(want, accountId, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => {
if (error.code) {
// Process service logic errors.
......@@ -908,9 +987,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result.
Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -928,19 +1007,26 @@ Stops a Service Extension ability in the same application with the account ID sp
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
try {
this.context.startAbilityWithAccount(want, accountId, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
.then((data) => {
// Carry out normal service processing.
......@@ -977,7 +1063,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1014,7 +1101,8 @@ Terminates this ability. This API uses a promise to return the result.
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1034,7 +1122,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void;
Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1050,7 +1138,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1088,8 +1177,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
## AbilityContext.terminateSelfWithResult
terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;;
Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1110,7 +1198,8 @@ Terminates this ability. This API uses a promise to return the ability result in
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1173,15 +1262,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
......@@ -1204,9 +1294,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number;
Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified.
Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability with the account ID specified.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1231,15 +1321,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -1283,7 +1374,8 @@ Disconnects a connection. This API uses a promise to return the result.
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1329,7 +1421,8 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1361,6 +1454,11 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
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.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -1388,7 +1486,7 @@ Starts an ability in the foreground or background and obtains the caller object
var wantBackground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
};
......@@ -1419,7 +1517,7 @@ Starts an ability in the foreground or background and obtains the caller object
var wantForeground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: "",
parameters: {
"ohos.aafwk.param.callAbilityToForeground": true
......@@ -1450,7 +1548,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1469,15 +1572,16 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -1506,7 +1610,12 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1526,15 +1635,16 @@ Starts an ability with the account ID and start options specified. This API uses
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -1566,7 +1676,12 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
Starts an ability with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1585,15 +1700,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -1618,65 +1734,6 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
}
```
## AbilityContext.requestPermissionsFromUser
requestPermissionsFromUser(permissions: Array&lt;string&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void;
Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| Permissions to request.|
| callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)&gt; | Yes| Callback used to return the result.|
**Example**
```ts
var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
});
```
## AbilityContext.requestPermissionsFromUser
requestPermissionsFromUser(permissions: Array&lt;string&gt;) : Promise&lt;PermissionRequestResult&gt;;
Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| Permissions to request.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)&gt; | Promise used to return the result.|
**Example**
```ts
var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
## AbilityContext.setMissionLabel
setMissionLabel(label: string, callback:AsyncCallback&lt;void&gt;): void;
......@@ -1696,7 +1753,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call
```ts
this.context.setMissionLabel("test",(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
console.log('setMissionLabel result:' + JSON.stringify(result));
});
```
......@@ -1744,7 +1801,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| icon | image.PixelMap | Yes| Icon of the ability to set.|
| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
......@@ -1786,7 +1843,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| icon | image.PixelMap | Yes| Icon of the ability to set.|
| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.|
**Return value**
......
# @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.featureAbility
# @ohos.ability.featureAbility (FeatureAbility)
The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability.
The **FeatureAbility** module provides APIs that enable user interaction. You can use the APIs to start or terminate an ability, obtain a **dataAbilityHelper** object, obtain the window corresponding to the current ability, and connect to or disconnect from a ServiceAbility.
> **NOTE**
>
......@@ -9,7 +9,7 @@ The **FeatureAbility** module provides a UI for interacting with users. You can
## Constraints
APIs of the **FeatureAbility** module can be called only by Page abilities.
The APIs of the **FeatureAbility** module can be called only by PageAbilities.
## Modules to Import
......@@ -23,6 +23,11 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<number>)
Starts an ability. 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
**Parameters**
......@@ -48,7 +53,7 @@ featureAbility.startAbility(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri: ""
},
},
......@@ -66,6 +71,11 @@ startAbility(parameter: StartAbilityParameter): Promise\<number>
Starts an ability. 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
**Parameters**
......@@ -74,6 +84,12 @@ Starts an ability. This API uses a promise to return the result.
| --------- | ---------------------------------------- | ---- | -------------- |
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<number> | Promise used to return the result.|
**Example**
```ts
......@@ -90,7 +106,7 @@ featureAbility.startAbility(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri: ""
},
}
......@@ -105,6 +121,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**
......@@ -117,7 +139,7 @@ Obtains a **dataAbilityHelper** object.
| Type | Description |
| ----------------- | ------------------------------- |
| DataAbilityHelper | A utility class used to help other abilities access the Data ability.|
| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access the Data ability.|
**Example**
......@@ -132,7 +154,12 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\<AbilityResult>): void
Starts an ability. This API uses an asynchronous callback to return the execution result when the ability is destroyed.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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
......@@ -159,7 +186,7 @@ featureAbility.startAbilityForResult(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri:""
},
},
......@@ -173,7 +200,12 @@ featureAbility.startAbilityForResult(
startAbilityForResult(parameter: StartAbilityParameter): Promise\<AbilityResult>
Starts an ability. This API uses a promise to return the execution result when the ability is destroyed.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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
......@@ -187,7 +219,7 @@ Starts an ability. This API uses a promise to return the execution result when t
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promised returned with the execution result.|
| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.|
**Example**
......@@ -205,7 +237,7 @@ featureAbility.startAbilityForResult(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri:"",
parameters:
{
......@@ -229,7 +261,7 @@ featureAbility.startAbilityForResult(
terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\<void>): void
Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -237,7 +269,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
| Name | Type | Mandatory | Description |
| --------- | ------------------------------- | ---- | -------------- |
| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.|
| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
......@@ -257,7 +289,7 @@ featureAbility.terminateSelfWithResult(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri:"",
parameters: {
mykey0: 2222,
......@@ -281,7 +313,7 @@ featureAbility.terminateSelfWithResult(
terminateSelfWithResult(parameter: AbilityResult): Promise\<void>
Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -289,7 +321,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
| Name | Type | Mandatory | Description |
| --------- | ------------------------------- | ---- | ------------- |
| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.|
| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.|
**Return value**
......@@ -314,7 +346,7 @@ featureAbility.terminateSelfWithResult(
deviceId: "",
bundleName: "com.example.myapplication",
/* In the FA model, abilityName consists of package and ability names. */
abilityName: "com.example.entry.secondAbility",
abilityName: "com.example.myapplication.secondAbility",
uri:"",
parameters: {
mykey0: 2222,
......@@ -345,7 +377,7 @@ Checks whether the main window of this ability has the focus. This API uses an a
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.<br>Returns **true** if the main window of this ability has the focus; returns **false** otherwise.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result.<br>If the main window has the focus, **true** is returned. Otherwise, **false** is returned.|
**Example**
......@@ -368,7 +400,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr
| Type | Description |
| ----------------- | ------------------------------------- |
| Promise\<boolean> | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.|
| Promise\<boolean> | Promise used to return the result. If the main window has the focus, **true** is returned. Otherwise, **false** is returned.|
**Example**
......@@ -383,7 +415,7 @@ featureAbility.hasWindowFocus().then((data) => {
getWant(callback: AsyncCallback\<Want>): void
Obtains the **Want** object sent from this ability. This API uses an asynchronous callback to return the result.
Obtains the Want corresponding to the ability to start. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -391,7 +423,7 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou
| Name | Type | Mandatory | Description |
| -------- | ----------------------------- | ---- | --------- |
| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the result.|
| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the Want.|
**Example**
......@@ -406,7 +438,7 @@ featureAbility.getWant((err, data) => {
getWant(): Promise\<Want>
Obtains the **Want** object sent from this ability. This API uses a promise to return the result.
Obtains the Want corresponding to the ability to start. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -414,7 +446,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r
| Type | Description |
| ----------------------- | ---------------- |
| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the result.|
| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the Want.|
**Example**
......@@ -453,7 +485,7 @@ context.getBundleName((err, data) => {
terminateSelf(callback: AsyncCallback\<void>): void
Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result.
Terminates this ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -478,7 +510,7 @@ featureAbility.terminateSelf(
terminateSelf(): Promise\<void>
Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result.
Terminates this ability. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -501,7 +533,13 @@ featureAbility.terminateSelf().then((data) => {
connectAbility(request: Want, options:ConnectOptions): number
Connects this ability to a specific Service ability. This API uses an asynchronous callback to return the result.
Connects this ability to a 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
......@@ -509,14 +547,14 @@ Connects this ability to a specific Service ability. This API uses an asynchrono
| Name | Type | Mandatory | Description |
| ------- | -------------- | ---- | --------------------- |
| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Callback used to return the result. |
| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. |
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | ID of the Service ability connected.|
| number | ID of the connected ServiceAbility. The ID starts from 0 and is incremented by 1 each time a connection is set up.|
**Example**
......@@ -536,7 +574,7 @@ var connectId = featureAbility.connectAbility(
{
deviceId: "",
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
abilityName: "com.ix.ServiceAbility.ServiceAbilityA",
},
{
onConnect: onConnectCallback,
......@@ -550,7 +588,7 @@ var connectId = featureAbility.connectAbility(
disconnectAbility(connection: number, callback:AsyncCallback\<void>): void
Disconnects this ability from a specific Service ability. This API uses an asynchronous 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
......@@ -558,7 +596,7 @@ Disconnects this ability from a specific Service ability. This API uses an async
| Name | Type | Mandatory | Description |
| ---------- | -------------------- | ---- | ----------------------- |
| connection | number | Yes | ID of the Service ability to disconnect.|
| connection | number | Yes | ID of the ServiceAbility to disconnect.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
......@@ -578,7 +616,7 @@ function onFailedCallback(code){
var connectId = featureAbility.connectAbility(
{
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
abilityName: "com.ix.ServiceAbility.ServiceAbilityA",
},
{
onConnect: onConnectCallback,
......@@ -597,7 +635,7 @@ var result = featureAbility.disconnectAbility(connectId,
disconnectAbility(connection: number): Promise\<void>
Disconnects this ability from a specific 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
......@@ -605,7 +643,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis
| Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ----------------------- |
| connection | number | Yes | ID of the Service ability to disconnect.|
| connection | number | Yes | ID of the ServiceAbility to disconnect.|
**Return value**
......@@ -630,7 +668,7 @@ function onFailedCallback(code){
var connectId = featureAbility.connectAbility(
{
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
abilityName: "com.ix.ServiceAbility.ServiceAbilityA",
},
{
onConnect: onConnectCallback,
......@@ -659,7 +697,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous
| Name | Type | Mandatory| Description |
| -------- | ----------------------------- | ---- | ----------------------------- |
| callback | AsyncCallback\<window.Window> | Yes | Callback used to return the window.|
| callback | AsyncCallback\<[window.Window](js-apis-window.md#window)> | Yes | Callback used to return the window.|
**Example**
......@@ -681,7 +719,7 @@ Obtains the window corresponding to this ability. This API uses a promise to ret
| Type | Description |
| ----------------------- | ----------------------------- |
| Promise\<window.Window> | Promise used to return the window.|
| Promise\<[window.Window](js-apis-window.md#window)> | Promise used to return the window.|
**Example**
......@@ -693,7 +731,7 @@ featureAbility.getWindow().then((data) => {
## AbilityWindowConfiguration
The value is obtained through the **featureAbility.AbilityWindowConfiguration** API.
Defines the window configuration corresponding to this ability. The configuration is obtained through **featureAbility.AbilityWindowConfiguration**.
**Example**
......@@ -705,18 +743,18 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED
| Name | Value | Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| WINDOW_MODE_UNDEFINED<sup>7+</sup> | 0 | The Page ability is in an undefined window display mode.|
| WINDOW_MODE_FULLSCREEN<sup>7+</sup> | 1 | The Page ability is in full screen mode. |
| WINDOW_MODE_SPLIT_PRIMARY<sup>7+</sup> | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.|
| WINDOW_MODE_SPLIT_SECONDARY<sup>7+</sup> | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.|
| WINDOW_MODE_FLOATING<sup>7+</sup> | 102 | The Page ability is displayed in floating window mode.|
| WINDOW_MODE_UNDEFINED<sup>7+</sup> | 0 | The PageAbility is in an undefined window display mode.|
| WINDOW_MODE_FULLSCREEN<sup>7+</sup> | 1 | The PageAbility is in full screen mode. |
| WINDOW_MODE_SPLIT_PRIMARY<sup>7+</sup> | 100 | The PageAbility is displayed in the primary window when it is in split-screen mode.|
| WINDOW_MODE_SPLIT_SECONDARY<sup>7+</sup> | 101 | The PageAbility is displayed in the secondary window when it is in split-screen mode.|
| WINDOW_MODE_FLOATING<sup>7+</sup> | 102 | The PageAbility is displayed in floating window mode.|
## AbilityStartSetting
The **AbilityStartSetting** attribute is an object defined as [key: string]: any. The key is a type of **AbilityStartSetting**, and the value is a type of **AbilityWindowConfiguration**.
Defines the window attribute corresponding to this ability. The **abilityStartSetting** attribute is an object defined in the format of [**key: string]: any**, where **key** is an enumerated value of **AbilityStartSetting** and **value** is an enumerated value of **AbilityWindowConfiguration**.
The value is obtained through the **featureAbility.AbilityStartSetting** API.
The value is obtained through **featureAbility.AbilityStartSetting**.
**Example**
......@@ -734,7 +772,7 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY
## ErrorCode
Enumerates error codes.
Enumerates the error codes.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -743,12 +781,12 @@ Enumerates error codes.
| NO_ERROR<sup>7+</sup> | 0 | No error occurs.|
| INVALID_PARAMETER<sup>7+</sup> | -1 | Invalid parameter.|
| ABILITY_NOT_FOUND<sup>7+</sup> | -2 | The ability is not found.|
| PERMISSION_DENY<sup>7+</sup> | -3 | The request is denied.|
| PERMISSION_DENY<sup>7+</sup> | -3 | Permission denied.|
## DataAbilityOperationType
Enumerates operation types of the Data ability.
Enumerates the operation types of a DataAbility. The DataAbility can use an enumerated value to specify the operation type when operating data in batches.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -761,23 +799,25 @@ Enumerates operation types of the Data ability.
## 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 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 migrated to a remote device. |
| FLAG_ABILITY_CONTINUATION | 0x00000008 | Continues the ability on a remote device. |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. |
| 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.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether the FormAbility is enabled. |
| 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 ability is started in the foreground regardless of whether the host application is started.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.|
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical 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 an existing 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.|
# @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 {
// 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|
| -------- | -------- | -------- | -------- | -------- |
| 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_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
......@@ -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
```ts
import UIAbility from "@ohos.app.ability.UIAbility";
**Example**
export default class MyAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
let AbilityLifecycleCallback = {
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 ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onAbilityCreate.");
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
console.log("AbilityLifecycleCallback onWindowStageCreate.");
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));
console.log("AbilityLifecycleCallback onWindowStageActive.");
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
console.log("AbilityLifecycleCallback onWindowStageInactive.");
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
console.log("AbilityLifecycleCallback onWindowStageDestroy.");
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onAbilityDestroy.");
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onAbilityForeground.");
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onAbilityBackground.");
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(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. 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));
},
// 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();
applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
// 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');
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success.');
}).catch((err) => {
console.log('updateConfiguration fail');
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))
abilityManager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + 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));
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + 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 {
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage.onCreate is called")
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 {
```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 {
```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.appManager
# @ohos.app.ability.appManager (appManager)
The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process.
......@@ -12,7 +12,7 @@ The **appManager** module implements application management. You can use the API
import appManager from '@ohos.app.ability.appManager';
```
## appManager.isRunningInStabilityTest<sup>9+</sup>
## appManager.isRunningInStabilityTest
static isRunningInStabilityTest(callback: AsyncCallback&lt;boolean&gt;): void
......@@ -22,21 +22,34 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
| Type| Description|
| -------- | -------- |
|AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.|
**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 app from '@ohos.application.appManager';
app.isRunningInStabilityTest((err, flag) => {
console.log('startAbility result:' + JSON.stringify(err));
})
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest((err, flag) => {
if (err.code !== 0) {
console.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err));
} else {
console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag));
}
})
```
## appManager.isRunningInStabilityTest<sup>9+</sup>
## appManager.isRunningInStabilityTest
static isRunningInStabilityTest(): Promise&lt;boolean&gt;
......@@ -48,18 +61,27 @@ Checks whether this application is undergoing a stability test. This API uses a
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
| Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.|
**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 app from '@ohos.application.appManager';
app.isRunningInStabilityTest().then((flag) => {
console.log('success:' + JSON.stringify(flag));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest().then((flag) => {
console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.isRamConstrainedDevice
......@@ -74,17 +96,27 @@ Checks whether this application is running on a RAM constrained device. This API
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
| Promise&lt;boolean&gt; | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
app.isRamConstrainedDevice().then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice().then((data) => {
console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.isRamConstrainedDevice
......@@ -96,18 +128,31 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
| Type| Description|
| -------- | -------- |
| AsyncCallback&lt;boolean&gt; |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
app.isRamConstrainedDevice((err, data) => {
console.log('startAbility result failed:' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
})
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice((err, data) => {
if (err.code !== 0) {
console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err));
} else {
console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data));
}
})
```
## appManager.getAppMemorySize
......@@ -121,17 +166,27 @@ Obtains the memory size of this application. This API uses a promise to return t
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.|
| Promise&lt;number&gt; | Promise used to return the API call result and the memory size. 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
app.getAppMemorySize().then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize().then((data) => {
console.log("The size of app memory is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.getAppMemorySize
......@@ -143,20 +198,33 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Size of the application memory.|
| Type| Description|
| -------- | -------- |
|AsyncCallback&lt;number&gt; |Callback used to return the API call result and the memory size. 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
app.getAppMemorySize((err, data) => {
console.log('startAbility result failed :' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
})
```
```ts
import appManager from '@ohos.app.ability.appManager';
## appManager.getProcessRunningInformation<sup>9+</sup>
appManager.getAppMemorySize((err, data) => {
if (err.code !== 0) {
console.log("getAppMemorySize faile, err: " + JSON.stringify(err));
} else {
console.log("The size of app memory is:" + JSON.stringify(data));
}
})
```
## appManager.getProcessRunningInformation
getProcessRunningInformation(): Promise\<Array\<ProcessRunningInformation>>;
......@@ -172,17 +240,27 @@ Obtains information about the running processes. This API uses a promise to retu
| Type| Description|
| -------- | -------- |
| Promise\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | Promise used to return the process information.|
| Promise\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | Promise used to return the API call result and the process 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
app.getProcessRunningInformation().then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.getProcessRunningInformation().then((data) => {
console.log("The process running information is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.getProcessRunningInformation<sup>9+</sup>
......@@ -198,18 +276,31 @@ Obtains information about the running processes. This API uses an asynchronous c
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | Yes| Callback used to return the process information.|
| Type| Description|
| -------- | -------- |
|AsyncCallback\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | Callback used to return the API call result and the process 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
app.getProcessRunningInformation((err, data) => {
console.log('startAbility result failed :' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
})
```
```ts
import appManager from '@ohos.app.ability.appManager';
appManager.getProcessRunningInformation((err, data) => {
if (err.code !== 0) {
console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err));
} else {
console.log("The process running information is:" + JSON.stringify(data));
}
})
```
## appManager.on
......@@ -227,37 +318,52 @@ Registers an observer to listen for the state changes of all applications.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.|
| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.|
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.|
**Return value**
| Type| Description|
| --- | --- |
| number | Digital code of the observer, which will be used in **off()** to deregister the observer.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
var applicationStateObserver = {
```ts
import appManager from '@ohos.app.ability.appManager';
let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log('------------ onForegroundApplicationChanged -----------', appStateData);
console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`);
},
onAbilityStateChanged(abilityStateData) {
console.log('------------ onAbilityStateChanged -----------', abilityStateData);
console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
},
onProcessCreated(processData) {
console.log('------------ onProcessCreated -----------', processData);
console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`);
},
onProcessDied(processData) {
console.log('------------ onProcessDied -----------', processData);
console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`);
},
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
}
try {
const observerCode = app.on(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
}
try {
const observerId = appManager.on('applicationState', applicationStateObserver);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
```
## appManager.on
......@@ -275,39 +381,55 @@ Registers an observer to listen for the state changes of a specified application
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.|
| bundleNameList | Array<string> | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.|
| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.|
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.|
| bundleNameList | `Array<string>` | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.|
**Return value**
| Type| Description|
| --- | --- |
| number | Digital code of the observer, which will be used in **off()** to deregister the observer.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```js
var applicationStateObserver = {
```ts
import appManager from '@ohos.app.ability.appManager';
let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log('------------ onForegroundApplicationChanged -----------', appStateData);
console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`);
},
onAbilityStateChanged(abilityStateData) {
console.log('------------ onAbilityStateChanged -----------', abilityStateData);
console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
},
onProcessCreated(processData) {
console.log('------------ onProcessCreated -----------', processData);
console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`);
},
onProcessDied(processData) {
console.log('------------ onProcessDied -----------', processData);
console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`);
},
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
}
}
var bundleNameList = ['bundleName1', 'bundleName2'];
try {
const observerCode = app.on("applicationState", applicationStateObserver, bundleNameList);
console.log('-------- observerCode: ---------', observerCode);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
}
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
const observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
```
```
## appManager.off
off(type: "applicationState", observerId: number, callback: AsyncCallback\<void>): void;
......@@ -324,26 +446,65 @@ Deregisters the application state observer. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Numeric code of the observer.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.|
| observerId | number | Yes| Digital code of the observer.|
| 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**
```js
var observerId = 100;
```ts
import appManager from '@ohos.app.ability.appManager';
function unregisterApplicationStateObserverCallback(err) {
if (err) {
console.log('------------ unregisterApplicationStateObserverCallback ------------', err);
let observeId = 0;
// 1. Register an application state observer.
let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`);
},
onAbilityStateChanged(abilityStateData) {
console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
},
onProcessCreated(processData) {
console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`);
},
onProcessDied(processData) {
console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`);
},
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
}
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
// 2. Deregister the application state observer.
function unregisterApplicationStateObserverCallback(err) {
if (err.code !== 0) {
console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err));
} else {
console.log("unregisterApplicationStateObserverCallback success.");
}
try {
app.off(observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) {
}
try {
appManager.off("applicationState", observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
}
```
## appManager.off
......@@ -361,38 +522,73 @@ Deregisters the application state observer. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Numeric code of the observer.|
| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.|
| observerId | number | Yes| Digital code of the observer.|
**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**
```js
var observerId = 100;
```ts
import appManager from '@ohos.app.ability.appManager';
try {
app.off(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err);
let observeId = 0;
// 1. Register an application state observer.
let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`);
},
onAbilityStateChanged(abilityStateData) {
console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`);
},
onProcessCreated(processData) {
console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`);
},
onProcessDied(processData) {
console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`);
},
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
}
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
// 2. Deregister the application state observer.
try {
appManager.off("applicationState", observerId).then((data) => {
console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err));
})
} catch (paramError) {
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
}
```
## appManager.getForegroundApplications
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result.
Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -400,96 +596,44 @@ Obtains applications that are running in the foreground. This API uses an asynch
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<AppStateData>> | Yes| Callback used to return the application state data.|
**Example**
**Error codes**
```js
function getForegroundApplicationsCallback(err, data) {
if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err.code + ': ' + err.message);
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data)
}
}
app.getForegroundApplications(getForegroundApplicationsCallback);
```
unregisterApplicationStateObserver(observerId: number): Promise\<void>;
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
Deregisters the application state observer. This API uses a promise to return the result.
**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Yes| Callback used to return the API call result and an array holding the application state data. You can perform error handling or custom processing in this callback.|
**Example**
```ts
var observerId = 100;
app.unregisterApplicationStateObserver(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err);
})
```
## appManager.getForegroundApplications<sup>9+</sup>
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<AppStateData>> | Yes| Callback used to return the application state data.|
**Example**
```ts
import appManager from '@ohos.app.ability.appManager';
```ts
function getForegroundApplicationsCallback(err, data) {
if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err);
function getForegroundApplicationsCallback(err, data) {
if (err.code !== 0) {
console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err));
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data)
}
console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data));
}
app.getForegroundApplications(getForegroundApplicationsCallback);
```
}
try {
appManager.getForegroundApplications(getForegroundApplicationsCallback);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appManager.getForegroundApplications<sup>9+</sup>
## appManager.getForegroundApplications
getForegroundApplications(): Promise\<Array\<AppStateData>>;
Obtains applications that are running in the foreground. This API uses a promise to return the result.
Obtains applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -501,27 +645,35 @@ Obtains applications that are running in the foreground. This API uses a promise
| Type| Description|
| -------- | -------- |
| Promise\<Array\<ProcessRunningInfo>> | Promise used to return the application state data.|
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return an array holding the application state data|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
app.getForegroundApplications()
.then((data) => {
console.log('--------- getForegroundApplications success -------', data);
})
.catch((err) => {
console.log('--------- getForegroundApplications fail -------', err);
})
```
```ts
import appManager from '@ohos.app.ability.appManager';
## appManager.killProcessWithAccount<sup>9+</sup>
appManager.getForegroundApplications().then((data) => {
console.log("getForegroundApplications success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getForegroundApplications fail, err: " + JSON.stringify(err));
})
```
## appManager.killProcessWithAccount
killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
Kills a process by bundle name and account ID. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -529,27 +681,39 @@ Kills a process by bundle name and account ID. This API uses a promise to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var bundleName = 'bundleName';
var accountId = 0;
app.killProcessWithAccount(bundleName, accountId)
.then((data) => {
console.log('------------ killProcessWithAccount success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessWithAccount fail ------------', err);
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
let accountId = 0;
try {
appManager.killProcessWithAccount(bundleName, accountId).then(() => {
console.log("killProcessWithAccount success");
}).catch((err) => {
console.log("killProcessWithAccount fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appManager.killProcessWithAccount<sup>9+</sup>
## appManager.killProcessWithAccount
killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\<void\>): void
......@@ -559,32 +723,42 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
| 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
var bundleName = 'bundleName';
var accountId = 0;
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
let accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err) {
console.log('------------- killProcessWithAccountCallback fail, err: --------------', err);
if (err.code !== 0) {
console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err));
} else {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
console.log("killProcessWithAccountCallback success.");
}
}
app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
```
## appManager.killProcessesByBundleName<sup>9+</sup>
## appManager.killProcessesByBundleName
killProcessesByBundleName(bundleName: string, callback: AsyncCallback\<void>);
......@@ -600,24 +774,38 @@ Kills a process by bundle name. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
| bundleName | string | Yes| Bundle name.|
| 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
var bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err) {
console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
```ts
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err.code !== 0) {
console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err));
} else {
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
console.log("killProcessesByBundleNameCallback success.");
}
}
app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
```
}
try {
appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appManager.killProcessesByBundleName<sup>9+</sup>
## appManager.killProcessesByBundleName
killProcessesByBundleName(bundleName: string): Promise\<void>;
......@@ -633,7 +821,7 @@ Kills a process by bundle name. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
**Return value**
......@@ -641,20 +829,32 @@ Kills a process by bundle name. This API uses a promise to return the result.
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
var bundleName = 'bundleName';
app.killProcessesByBundleName(bundleName)
.then((data) => {
console.log('------------ killProcessesByBundleName success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessesByBundleName fail ------------', err);
```ts
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
try {
appManager.killProcessesByBundleName(bundleName).then((data) => {
console.log("killProcessesByBundleName success.");
}).catch((err) => {
console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err));
})
```
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appManager.clearUpApplicationData<sup>9+</sup>
## appManager.clearUpApplicationData
clearUpApplicationData(bundleName: string, callback: AsyncCallback\<void>);
......@@ -670,24 +870,38 @@ Clears application data by bundle name. This API uses an asynchronous callback t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
| bundleName | string | Yes| Bundle name.|
| 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
var bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
```ts
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err) {
console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err);
console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err));
} else {
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
}
console.log("clearUpApplicationDataCallback success.");
}
app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
```
}
try {
appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## appManager.clearUpApplicationData<sup>9+</sup>
## appManager.clearUpApplicationData
clearUpApplicationData(bundleName: string): Promise\<void>;
......@@ -703,28 +917,42 @@ Clears application data by bundle name. This API uses a promise to return the re
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
**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
var bundleName = 'bundleName';
app.clearUpApplicationData(bundleName)
.then((data) => {
console.log('------------ clearUpApplicationData success ------------', data);
})
.catch((err) => {
console.log('------------ clearUpApplicationData fail ------------', err);
```ts
import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
try {
appManager.clearUpApplicationData(bundleName).then((data) => {
console.log("clearUpApplicationData success.");
}).catch((err) => {
console.log("clearUpApplicationData fail, err: " + JSON.stringify(err));
})
```
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
## ApplicationState<sup>9+</sup>
## ApplicationState
Enumerates the application states. This enum can be used together with [AbilityStateData](js-apis-inner-application-appStateData.md) to return the application state.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -738,7 +966,9 @@ Clears application data by bundle name. This API uses a promise to return the re
| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. |
| STATE_DESTROY | 5 | State indicating that the application is destroyed. |
## ProcessState<sup>9+</sup>
## ProcessState
Enumerates the process states. This enum can be used together with [ProcessData](js-apis-inner-application-processData.md) to return the process state.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
# @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,12 +14,12 @@ 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.|
......@@ -28,6 +28,10 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi
**Example**
```ts
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)}`)
......@@ -40,8 +44,12 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi
}
};
try {
var callbackId = applicationContext.on("environment", envCallback);
let applicationContext = this.context.getApplicationContext();
let callbackId = applicationContext.on("environment", envCallback);
console.log("callbackId: " + callbackId);
} 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**
>
......@@ -21,5 +21,5 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM
| 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.EnvironmentCallback
# @ohos.app.ability.EnvironmentCallback (EnvironmentCallback)
The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes.
......@@ -33,18 +33,18 @@ Called when the system environment changes.
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from "@ohos.app.ability.Ability";
var callbackId;
export default class MyAbility extends Ability {
export default class MyAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
}
}
// 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext;
......
# @ohos.app.ability.errorManager (Error Manager)
# @ohos.app.ability.errorManager (ErrorManager)
The **errorManager** module provides APIs for registering and deregistering error observers.
The **ErrorManager** module provides APIs for registering and deregistering error observers. For example, you can use the APIs to register an observer when your application wants to capture JS crashes.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
```ts
import errorManager from '@ohos.app.ability.errorManager'
```
......@@ -23,19 +23,26 @@ Registers an error observer.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.|
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.|
| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Index of the observer.|
**Example**
```js
```ts
var observer = {
onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg)
}
}
var observerId = -1;
try {
errorManager.on("error", observer);
observerId = errorManager.on("error", observer);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
......@@ -53,13 +60,13 @@ Deregisters an error observer. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Numeric code of the observer.|
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.|
| observerId | number | Yes| Index of the observer returned by **on()**.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
```ts
var observerId = 100;
function unregisterErrorObserverCallback(err) {
......@@ -86,8 +93,8 @@ Deregisters an error observer. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Numeric code of the observer.|
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.|
| observerId | number | Yes| Index of the observer returned by **on()**.|
**Return value**
......@@ -97,7 +104,7 @@ Deregisters an error observer. This API uses a promise to return the result.
**Example**
```js
```ts
var observerId = 100;
try {
errorManager.off("error", observerId)
......
# @ohos.app.ability.ExtensionAbility
# @ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class)
The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information.
**ExtensionAbility** is the base class for scenario-specific ExtensionAbilities. It is inherited from [Ability](js-apis-app-ability-ability.md), with no attribute or method added. 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 ExtensionAbility from '@ohos.app.ability.ExtensionAbility';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
```ts
class MyExtensionAbility extends ExtensionAbility {
onConfigurationUpdated(config) {
console.log('onConfigurationUpdated, config:' + JSON.stringify(config));
}
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
# @ohos.app.ability.missionManager
# @ohos.app.ability.missionManager (missionManager)
The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground.
......@@ -9,7 +9,7 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions,
## Modules to Import
```ts
import missionManager from '@ohos.app.ability.missionManager'
import missionManager from '@ohos.app.ability.missionManager';
```
## Required Permissions
......@@ -32,19 +32,19 @@ Registers a listener to observe the mission status.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listener | MissionListener | Yes| Listener to register.|
| listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.|
| number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
import missionManager from '@ohos.app.ability.missionManager';
import UIAbility from '@ohos.app.ability.UIAbility';
var listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")},
......@@ -52,14 +52,15 @@ var listener = {
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")},
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")},
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")}
};
var listenerId = -1;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate");
globalThis.abilityWant = want;
globalThis.context = this.context;
}
......@@ -74,12 +75,12 @@ export default class MainAbility extends Ability {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] MainAbility onDestroy")
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
......@@ -106,7 +107,7 @@ export default class MainAbility extends Ability {
off(type: "mission", listenerId: number, callback: AsyncCallback&lt;void&gt;): void;
Deregisters a mission status listener. This API uses an asynchronous callback to return the result.
Deregisters a mission status listener.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
......@@ -118,14 +119,14 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.|
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
import Ability from '@ohos.application.Ability'
import missionManager from '@ohos.app.ability.missionManager';
import UIAbility from '@ohos.app.ability.UIAbility';
var listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")},
......@@ -133,14 +134,15 @@ var listener = {
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")},
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")},
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")}
};
var listenerId = -1;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want;
globalThis.context = this.context;
}
......@@ -155,12 +157,12 @@ export default class MainAbility extends Ability {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] MainAbility onDestroy")
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
......@@ -199,7 +201,7 @@ Deregisters a mission status listener. This API uses a promise to return the res
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.|
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.|
**Return value**
......@@ -210,8 +212,8 @@ Deregisters a mission status listener. This API uses a promise to return the res
**Example**
```ts
import Ability from '@ohos.application.Ability'
import missionManager from '@ohos.app.ability.missionManager';
import UIAbility from '@ohos.app.ability.UIAbility';
var listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")},
......@@ -219,14 +221,15 @@ var listener = {
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")},
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")},
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")}
};
var listenerId = -1;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want;
globalThis.context = this.context;
}
......@@ -241,12 +244,12 @@ export default class MainAbility extends Ability {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] MainAbility onDestroy")
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
......@@ -292,18 +295,27 @@ Obtains the information about a given mission. This API uses an asynchronous cal
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 1;
try {
var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);});
missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => {
console.log("getMissionInfo is called, error.code = " + error.code)
var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);});
if (allMissions && allMissions.length > 0) {
testMissionId = allMissions[0].missionId;
}
missionManager.getMissionInfo("", testMissionId, (error, mission) => {
if (error) {
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
} else {
console.log("mission.missionId = " + mission.missionId);
console.log("mission.runningState = " + mission.runningState);
console.log("mission.lockedState = " + mission.lockedState);
console.log("mission.timestamp = " + mission.timestamp);
console.log("mission.label = " + mission.label);
console.log("mission.iconPath = " + mission.iconPath);
}
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
......@@ -338,18 +350,20 @@ Obtains the information about a given mission. This API uses a promise to return
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var mission = missionManager.getMissionInfo("", 10).catch(function (err){
console.log(err);
let testMissionId = 1;
try {
missionManager.getMissionInfo("", testMissionId).then((data) => {
console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('getMissionInfo failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('getMissionInfo failed. Cause: ' + error.message);
}
```
## missionManager.getMissionInfos
......@@ -374,13 +388,17 @@ Obtains information about all missions. This API uses an asynchronous callback t
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
import missionManager from '@ohos.app.ability.missionManager';
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
} else {
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
}
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
......@@ -415,18 +433,19 @@ Obtains information about all missions. This API uses a promise to return the re
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){
console.log(err);
try {
missionManager.getMissionInfos("", 10).then((data) => {
console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('getMissionInfos failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('getMissionInfos failed. Cause: ' + error.message);
}
```
## missionManager.getMissionSnapShot
......@@ -449,27 +468,22 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback
| callback | AsyncCallback&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Yes| Callback used to return the snapshot information obtained.|
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getMissionSnapShot("", id, (error, snapshot) => {
console.log("getMissionSnapShot is called, error.code = " + error.code);
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.getMissionSnapShot("", testMissionId, (err, data) => {
if (err) {
console.error('getMissionSnapShot failed:' + err.message);
} else {
console.info('getMissionSnapShot successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('getMissionSnapShot failed:' + err.message);
}
```
## missionManager.getMissionSnapShot
......@@ -497,26 +511,20 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r
| Promise&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Promise used to return the snapshot information obtained.|
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.getMissionSnapShot("", testMissionId).then((data) => {
console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('getMissionSnapShot failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('getMissionSnapShot failed. Cause: ' + error.message);
}
```
## missionManager.getLowResolutionMissionSnapShot
......@@ -539,27 +547,22 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr
| callback | AsyncCallback&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Yes| Callback used to return the snapshot information obtained.|
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => {
console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code);
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => {
if (err) {
console.error('getLowResolutionMissionSnapShot failed:' + err.message);
} else {
console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('getLowResolutionMissionSnapShot failed:' + err.message);
}
```
## missionManager.getLowResolutionMissionSnapShot
......@@ -588,25 +591,20 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => {
console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message);
}
```
## missionManager.lockMission
......@@ -630,25 +628,22 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
```ts
import missionManager from '@ohos.app.ability.missionManager';
missionManager.lockMission(id).then(() => {
console.log("lockMission is called ");
});
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.lockMission(testMissionId, (err, data) => {
if (err) {
console.error('lockMission failed:' + err.message);
} else {
console.info('lockMission successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('lockMission failed:' + err.message);
}
```
## missionManager.lockMission
......@@ -675,27 +670,20 @@ Locks a given mission. This API uses a promise to return the result.
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.lockMission(testMissionId).then((data) => {
console.info('lockMission successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('lockMission failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('lockMission failed. Cause: ' + error.message);
}
```
## missionManager.unlockMission
......@@ -717,26 +705,22 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.unlockMission(id).then(() => {
console.log("unlockMission is called ");
});
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.unlockMission(testMissionId, (err, data) => {
if (err) {
console.error('unlockMission failed:' + err.message);
} else {
console.info('unlockMission successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('unlockMission failed:' + err.message);
}
```
## missionManager.unlockMission
......@@ -764,29 +748,20 @@ Unlocks a given mission. This API uses a promise to return the result.
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){
console.log(err);
});
missionManager.unlockMission(id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.unlockMission(testMissionId).then((data) => {
console.info('unlockMission successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('unlockMission failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('unlockMission failed. Cause: ' + error.message);
}
```
## missionManager.clearMission
......@@ -809,24 +784,22 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
```ts
import missionManager from '@ohos.app.ability.missionManager';
missionManager.clearMission(id).then(() => {
console.log("clearMission is called ");
});
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.clearMission(testMissionId, (err, data) => {
if (err) {
console.error('clearMission failed:' + err.message);
} else {
console.info('clearMission successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('clearMission failed:' + err.message);
}
```
## missionManager.clearMission
......@@ -855,26 +828,20 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
missionManager.clearMission(id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.clearMission(testMissionId).then((data) => {
console.info('clearMission successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('clearMission failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('clearMission failed. Cause: ' + error.message);
}
```
## missionManager.clearAllMissions
......@@ -890,14 +857,21 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
missionManager.clearAllMissions().then(() => {
console.log("clearAllMissions is called ");
try {
missionManager.clearAllMissions(err => {
if (err) {
console.error('clearAllMissions failed:' + err.message);
} else {
console.info('clearAllMissions successfully.');
}
});
```
} catch (err) {
console.error('clearAllMissions failed:' + err.message);
}
```
## missionManager.clearAllMissions
......@@ -919,13 +893,19 @@ Clears all unlocked missions. This API uses a promise to return the result.
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
missionManager.clearAllMissions().catch(function (err){
console.log(err);
});
```
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
missionManager.clearAllMissions(bundleName).then(() => {
console.info('clearAllMissions successfully.');
}).catch(err => {
console.error('clearAllMissions failed:' + err.message);
});
} catch (err) {
console.error('clearAllMissions failed:' + err.message);
}
```
## missionManager.moveMissionToFront
......@@ -948,25 +928,22 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
```ts
import missionManager from '@ohos.app.ability.missionManager';
missionManager.moveMissionToFront(id).then(() => {
console.log("moveMissionToFront is called ");
});
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.moveMissionToFront(testMissionId, (err, data) => {
if (err) {
console.error('moveMissionToFront failed:' + err.message);
} else {
console.info('moveMissionToFront successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('moveMissionToFront failed:' + err.message);
}
```
## missionManager.moveMissionToFront
......@@ -990,25 +967,22 @@ Switches a given mission to the foreground, with the startup parameters for the
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
```ts
import missionManager from '@ohos.app.ability.missionManager';
missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => {
console.log("moveMissionToFront is called ");
});
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
let testMissionId = 2;
try {
missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => {
if (err) {
console.error('moveMissionToFront failed:' + err.message);
} else {
console.info('moveMissionToFront successfully:' + JSON.stringify(data));
}
```
});
} catch (err) {
console.error('moveMissionToFront failed:' + err.message);
}
```
## missionManager.moveMissionToFront
......@@ -1037,22 +1011,17 @@ Switches a given mission to the foreground, with the startup parameters for the
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager'
```ts
import missionManager from '@ohos.app.ability.missionManager';
try {
var allMissions;
missionManager.getMissionInfos("",10).then(function(res){
allMissions=res;
}).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions));
var id = allMissions[0].missionId;
missionManager.moveMissionToFront(id).catch(function (err){
console.log(err);
let testMissionId = 2;
try {
missionManager.moveMissionToFront(testMissionId).then((data) => {
console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('moveMissionToFront failed. Cause: ' + error.message);
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
} catch (error) {
console.error('moveMissionToFront failed. Cause: ' + error.message);
}
```
# @ohos.app.ability.quickFixManager
# @ohos.app.ability.quickFixManager (quickFixManager)
The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application.
......@@ -36,7 +36,7 @@ Defines the quick fix information at the application level.
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Bundle name of the application. |
| bundleName | string | Yes | Bundle name. |
| bundleVersionCode | number | Yes | Internal version number of the application. |
| bundleVersionName | string | Yes | Version number of the application that is shown to users. |
| quickFixVersionCode | number | Yes | Version code of the quick fix patch package. |
......@@ -65,8 +65,6 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
**Example**
```ts
import quickFixManager from '@ohos.app.ability.quickFixManager'
try {
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
......@@ -108,8 +106,6 @@ Applies a quick fix patch. This API uses a promise to return the result.
**Example**
```ts
import quickFixManager from '@ohos.app.ability.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
try {
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
......@@ -136,16 +132,14 @@ Obtains the quick fix information of the application. This API uses an asynchron
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes|Bundle name of the application. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes|Bundle name. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
**Example**
```ts
import quickFixManager from '@ohos.app.ability.quickFixManager'
try {
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
......@@ -174,9 +168,9 @@ Obtains the quick fix information of the application. This API uses a promise to
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of the application. |
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
**Return value**
......@@ -187,8 +181,6 @@ Obtains the quick fix information of the application. This API uses a promise to
**Example**
```ts
import quickFixManager from '@ohos.app.ability.quickFixManager'
try {
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
......@@ -199,4 +191,4 @@ Obtains the quick fix information of the application. This API uses a promise to
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
```
# @ohos.app.ability.ServiceExtensionAbility
# @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)
The **ServiceExtensionAbility** module provides APIs for Service Extension abilities.
The **ServiceExtensionAbility** module provides lifecycle callbacks when a ServiceExtensionAbility (background service) is created, destroyed, connected, or disconnected.
> **NOTE**
>
> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
......@@ -25,14 +25,14 @@ None.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.|
| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| ServiceExtensionContext, which is inherited from **ExtensionContext**.|
## ServiceExtensionAbility.onCreate
onCreate(want: Want): void;
Called when a Service Extension ability is created to initialize the service logic.
Called when a ServiceExtensionAbility is created to initialize the service logic.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -40,9 +40,9 @@ Called when a Service Extension ability is created to initialize the service log
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.|
**Example**
......@@ -59,7 +59,7 @@ Called when a Service Extension ability is created to initialize the service log
onDestroy(): void;
Called when this Service Extension ability is destroyed to clear resources.
Called when this ServiceExtensionAbility is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -80,7 +80,7 @@ Called when this Service Extension ability is destroyed to clear resources.
onRequest(want: Want, startId: number): void;
Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started.
Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()**. The value of **startId** is incremented for each ability that is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -88,10 +88,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.|
| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.|
**Example**
......@@ -108,7 +108,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started
onConnect(want: Want): rpc.RemoteObject;
Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client.
Called following **onCreate()** when a ServiceExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -116,15 +116,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.|
**Return value**
| Type| Description|
| -------- | -------- |
| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.|
| Type| Description|
| -------- | -------- |
| rpc.RemoteObject | A **RemoteObject** object used for communication between the server and client.|
**Example**
......@@ -150,7 +150,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started
onDisconnect(want: Want): void;
Called when this Service Extension ability is disconnected.
Called when a client is disconnected from this ServiceExtensionAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -158,9 +158,9 @@ Called when this Service Extension ability is disconnected.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.|
**Example**
......@@ -176,7 +176,7 @@ Called when this Service Extension ability is disconnected.
onReconnect(want: Want): void;
Called when this Service Extension ability is reconnected.
Called when a new client attempts to connect to this ServiceExtensionAbility after all previous clients are disconnected. This capability is reserved.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -184,9 +184,9 @@ Called when this Service Extension ability is reconnected.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.|
**Example**
......@@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected.
onConfigurationUpdate(newConfig: Configuration): void;
Called when the configuration of this Service Extension ability is updated.
Called when the configuration of this ServiceExtensionAbility is updated.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -210,9 +210,9 @@ Called when the configuration of this Service Extension ability is updated.
**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**
......@@ -236,9 +236,9 @@ Dumps the client information.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
......
# @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.|
# @ohos.app.ability.UIAbility
# @ohos.app.ability.UIAbility (UIAbility)
The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration:
This module provides the following common ability-related functions:
- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications.
- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee).
- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller).
> **NOTE**
>
......@@ -15,7 +13,7 @@ This module provides the following common ability-related functions:
## Modules to Import
```ts
import Ability from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility';
```
## Attributes
......@@ -24,30 +22,30 @@ import Ability from '@ohos.app.ability.UIAbility';
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.|
| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.|
| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.|
| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.|
| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.|
| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
## Ability.onCreate
## UIAbility.onCreate
onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
Called to initialize the service logic when an ability is created.
Called to initialize the service logic when a UIAbility is created.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.|
| param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.|
| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.|
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onCreate(want, param) {
console.log('onCreate, want:' + want.abilityName);
}
......@@ -55,24 +53,24 @@ Called to initialize the service logic when an ability is created.
```
## Ability.onWindowStageCreate
## UIAbility.onWindowStageCreate
onWindowStageCreate(windowStage: window.WindowStage): void
Called when a **WindowStage** is created for this ability.
Called when a **WindowStage** is created for this UIAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate');
}
......@@ -80,18 +78,18 @@ Called when a **WindowStage** is created for this ability.
```
## Ability.onWindowStageDestroy
## UIAbility.onWindowStageDestroy
onWindowStageDestroy(): void
Called when the **WindowStage** is destroyed for this ability.
Called when the **WindowStage** is destroyed for this UIAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onWindowStageDestroy() {
console.log('onWindowStageDestroy');
}
......@@ -99,24 +97,24 @@ Called when the **WindowStage** is destroyed for this ability.
```
## Ability.onWindowStageRestore
## UIAbility.onWindowStageRestore
onWindowStageRestore(windowStage: window.WindowStage): void
Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability.
Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onWindowStageRestore(windowStage) {
console.log('onWindowStageRestore');
}
......@@ -124,18 +122,18 @@ Called when the **WindowStage** is restored during the migration of this ability
```
## Ability.onDestroy
## UIAbility.onDestroy
onDestroy(): void;
Called when this ability is destroyed to clear resources.
Called when this UIAbility is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onDestroy() {
console.log('onDestroy');
}
......@@ -143,18 +141,18 @@ Called when this ability is destroyed to clear resources.
```
## Ability.onForeground
## UIAbility.onForeground
onForeground(): void;
Called when this ability is switched from the background to the foreground.
Called when this UIAbility is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onForeground() {
console.log('onForeground');
}
......@@ -162,18 +160,18 @@ Called when this ability is switched from the background to the foreground.
```
## Ability.onBackground
## UIAbility.onBackground
onBackground(): void;
Called when this ability is switched from the foreground to the background.
Called when this UIAbility is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onBackground() {
console.log('onBackground');
}
......@@ -181,7 +179,7 @@ Called when this ability is switched from the foreground to the background.
```
## Ability.onContinue
## UIAbility.onContinue
onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;
......@@ -191,21 +189,21 @@ Called to save data during the ability migration preparation process.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value**
| Type| Description|
| -------- | -------- |
| AbilityConstant.OnContinueResult | Continuation result.|
| Type| Description|
| -------- | -------- |
| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.|
**Example**
```ts
import AbilityConstant from "@ohos.application.AbilityConstant"
class myAbility extends Ability {
import AbilityConstant from "@ohos.app.ability.AbilityConstant"
class MyUIAbility extends UIAbility {
onContinue(wantParams) {
console.log('onContinue');
wantParams["myData"] = "my1234567";
......@@ -215,32 +213,33 @@ Called to save data during the ability migration preparation process.
```
## Ability.onNewWant
## UIAbility.onNewWant
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;
Called when the ability startup mode is set to singleton.
Called when a new Want is passed in and this UIAbility is started again.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.|
| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.|
**Example**
```ts
class myAbility extends Ability {
onNewWant(want) {
class MyUIAbility extends UIAbility {
onNewWant(want, launchParams) {
console.log('onNewWant, want:' + want.abilityName);
console.log('onNewWant, launchParams:' + JSON.stringify(launchParams));
}
}
```
## Ability.onDump
## UIAbility.onDump
onDump(params: Array\<string>): Array\<string>;
......@@ -250,14 +249,14 @@ Dumps client information.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
```ts
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onDump(params) {
console.log('dump, params:' + JSON.stringify(params));
return ["params"]
......@@ -266,33 +265,33 @@ Dumps client information.
```
## Ability.onSaveState
## UIAbility.onSaveState
onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;
Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md).
Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.|
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.|
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value**
| Type| Description|
| -------- | -------- |
| AbilityConstant.OnSaveResult | Whether the ability state is saved.|
| Type| Description|
| -------- | -------- |
| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.|
**Example**
```ts
import AbilityConstant from '@ohos.application.AbilityConstant'
import AbilityConstant from '@ohos.app.ability.AbilityConstant'
class myAbility extends Ability {
class MyUIAbility extends UIAbility {
onSaveState(reason, wantParam) {
console.log('onSaveState');
wantParam["myData"] = "my1234567";
......@@ -305,7 +304,7 @@ class myAbility extends Ability {
## Caller
Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility).
## Caller.call
......@@ -317,29 +316,29 @@ Sends sequenceable data to the target ability.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return a response.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return a response.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{ // Custom sequenceable data structure
class MyMessageAble{ // Custom sequenceable data structure.
name:""
str:""
num: 1
......@@ -360,13 +359,13 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
return true;
}
};
var method = 'call_Function'; // Notification message string negotiated by the two abilities
var method = 'call_Function'; // Notification message string negotiated by the two abilities.
var caller;
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
this.context.startUIAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "MainUIAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -398,28 +397,28 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)&gt; | Promise used to return the sequenceable data from the target ability.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{
name:""
str:""
......@@ -443,11 +442,11 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
};
var method = 'call_Function';
var caller;
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
this.context.startUIAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "MainUIAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -491,13 +490,12 @@ Releases the caller interface of the target ability.
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
var caller;
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
this.context.startUIAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "MainUIAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -525,20 +523,19 @@ Registers a callback that is invoked when the stub on the target ability is disc
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.|
**Example**
```ts
import Ability from '@ohos.application.Ability';
var caller;
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
this.context.startUIAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "MainUIAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -568,28 +565,28 @@ Registers a callback that is invoked when the stub on the target ability is disc
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
| callback | OnReleaseCallback | Yes| Callback used for the **onRelease** API.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
var caller;
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
this.context.startUIAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "MainUIAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -624,22 +621,22 @@ Registers a caller notification callback, which is invoked when the target abili
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | CalleeCallback | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{
name:""
str:""
......@@ -668,7 +665,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
pdata.readSequenceable(msg);
return new MyMessageAble("test1", "Callee test");
}
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onCreate(want, launchParam) {
console.log('Callee onCreate is called');
try {
......@@ -691,24 +688,24 @@ Deregisters a caller notification callback, which is invoked when the target abi
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Registered notification message string.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Registered notification message string.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
var method = 'call_Function';
export default class MainAbility extends Ability {
export default class MainUIAbility extends UIAbility {
onCreate(want, launchParam) {
console.log('Callee onCreate is called');
try {
......@@ -739,4 +736,4 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| Name| Readable| Writable| Type| Description|
| -------- | -------- | -------- | -------- | -------- |
| (indata: rpc.MessageParcel) | Yes| No| rpc.Sequenceable | Prototype of the listener function registered by the callee.|
| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.|
# @ohos.app.ability.Want
# @ohos.app.ability.Want (Want)
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When UIAbility A needs to start UIAbility B and transfer some data to UIAbility B, it can use Want a carrier to transfer the data.
> **NOTE**
>
......@@ -18,26 +18,26 @@ import Want from '@ohos.app.ability.Want';
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. |
| bundleName | string | No | Bundle name of the ability.|
| moduleName | string | No| Name of the module to which the ability belongs.|
| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. |
| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).|
| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. |
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. |
| moduleName | string | No | Module to which the ability belongs.|
| [action](js-apis-app-ability-wantConstant.md#wantConstant.Action) | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). |
| [entities](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | Array\<string> | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.|
| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No| MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.|
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>- **ohos.aafwk.callerPid**: PID of the caller.<br>- **ohos.aafwk.param.callerToken**: token of the caller.<br>- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. |
| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.<br>For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.|
**Example**
- Basic usage
- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility).
```ts
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "FuncAbility",
"moduleName": "entry" // moduleName is optional.
};
this.context.startAbility(want, (error) => {
......@@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want';
})
```
- Data is transferred through user-defined fields. The following data types are supported:
- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility):
* String
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForString: "str",
},
......@@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want';
* Number
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForInt: 100,
keyForDouble: 99.99,
......@@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want';
* Boolean
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForBool: true,
},
......@@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want';
* Object
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForObject: {
keyForObjectString: "str",
......@@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want';
* Array
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForArrayString: ["str1", "str2", "str3"],
keyForArrayInt: [100, 200, 300, 400],
......@@ -110,16 +110,16 @@ import Want from '@ohos.app.ability.Want';
* File descriptor (FD)
```ts
import fileio from '@ohos.fileio';
var fd;
let fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "FuncAbility",
"moduleName": "entry", // moduleName is optional.
"parameters": {
"keyFd":{"type":"FD", "value":fd}
......@@ -131,4 +131,6 @@ import Want from '@ohos.app.ability.Want';
})
```
- For more details and examples, see [Want](../../application-models/want-overview.md).
<!--no_check-->
# @ohos.app.ability.wantAgent
# @ohos.app.ability.wantAgent (WantAgent)
The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future.
......
# @ohos.app.ability.wantConstant
# @ohos.app.ability.wantConstant (wantConstant)
The **wantConstant** module provides the actions, entities, and flags used in **Want** objects.
......@@ -14,7 +14,7 @@ import wantConstant from '@ohos.app.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
......@@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object.
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. |
| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. |
| ACTION_FILE_SELECT | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | |
| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. |
| ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | Action of providing the authentication service. |
| ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
......@@ -56,7 +56,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
......@@ -71,7 +71,7 @@ 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
......@@ -79,17 +79,4 @@ Describes flags.
| ------------------------------------ | ---------- | ------------------------------------------------------------ |
| 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_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_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.|
# @ohos.app.form.formBindingData
# @ohos.application.formBindingData (formBindingData)
The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information.
......@@ -48,20 +48,17 @@ Creates a **FormBindingData** object.
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
context.getOrCreateLocalDir((err,data)=>{
let path=data+"/xxx.jpg";
let fd = fileio.openSync(path);
import fs from '@ohos.file.fs';
import formBindingData from '@ohos.app.form.formBindingData';
try {
let fd = fs.openSync('/path/to/form.png')
let obj = {
"temperature": "21°",
"formImages": {"image": fd}
"formImages": { "image": fd }
};
try {
formBindingData.createFormBindingData(obj);
} catch (error) {
console.log(`catch err->${JSON.stringify(err)}`);
}
})
} catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
# @ohos.app.form.FormExtensionAbility
# @ohos.app.form.FormExtensionAbility (FormExtensionAbility)
The **FormExtensionAbility** module provides APIs related to Form Extension abilities.
The **FormExtensionAbility** module provides lifecycle callbacks invoked when a widget is created, destroyed, or updated.
> **NOTE**
>
......@@ -18,8 +18,8 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
**System capability**: SystemCapability.Ability.Form
| Name | Type | Readable| Writable| Description |
| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- |
| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtensionAbility**. This context is inherited from **ExtensionContext**.|
| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the FormExtensionAbility. This context is inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).|
## onAddForm
......@@ -33,7 +33,7 @@ Called to notify the widget provider that a **Form** instance (widget) has been
| Name| Type | Mandatory| Description |
| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | Yes | Information related to the Extension ability, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.|
| want | [Want](js-apis-application-want.md) | Yes | Want information related to the FormExtensionAbility, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.|
**Return value**
......@@ -45,17 +45,19 @@ Called to notify the widget provider that a **Form** instance (widget) has been
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) {
console.log('FormExtensionAbility onAddForm, want:' + want.abilityName);
let dataObj1 = {
temperature:"11c",
"time":"11:00"
temperature: "11c",
"time": "11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
}
};
```
## onCastToNormalForm
......@@ -75,18 +77,20 @@ Called to notify the widget provider that a temporary widget has been converted
**Example**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId) {
console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId);
}
}
};
```
## onUpdateForm
onUpdateForm(formId: string): void
Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data.
Called to notify the widget provider that a widget has been updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data.
**System capability**: SystemCapability.Ability.Form
......@@ -99,17 +103,24 @@ Called to notify the widget provider that a widget has been updated. After obtai
**Example**
```ts
import formBindingData from '@ohos.app.form.formBindingData'
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId) {
console.log('FormExtensionAbility onUpdateForm, formId:' + formId);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
this.context.updateForm(formId, obj2).then((data)=>{
let obj2 = formBindingData.createFormBindingData({
temperature: "22c",
time: "22:00"
});
formProvider.updateForm(formId, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
console.error('Operation updateForm failed. Cause: ' + error);
});
}
}
};
```
## onChangeFormVisibility
......@@ -129,21 +140,28 @@ Called to notify the widget provider of the change of visibility.
**Example**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'
import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
let obj2 = formBindingData.createFormBindingData({
temperature: "22c",
time: "22:00"
});
for (let key in newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]);
this.context.updateForm(key, obj2).then((data)=>{
formProvider.updateForm(key, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
console.error('Operation updateForm failed. Cause: ' + error);
});
}
}
}
};
```
## onFormEvent
......@@ -164,11 +182,13 @@ Called to instruct the widget provider to receive and process the widget event.
**Example**
```ts
export default class MyFormExtension extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
}
}
};
```
## onRemoveForm
......@@ -188,11 +208,13 @@ Called to notify the widget provider that a **Form** instance (widget) has been
**Example**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId) {
console.log('FormExtensionAbility onRemoveForm, formId:' + formId);
}
}
};
```
## onConfigurationUpdate
......@@ -207,16 +229,18 @@ Called when the configuration of the environment where the ability is running is
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| newConfig | [Configuration](js-apis-configuration.md) | Yes| New configuration.|
| newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.|
**Example**
```ts
class MyFormExtensionAbility extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
};
```
## onAcquireFormState
......@@ -236,13 +260,15 @@ Called when the widget provider receives the status query result of a widget. By
**Example**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formInfo from '@ohos.app.form.formInfo';
class MyFormExtensionAbility extends FormExtensionAbility {
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState(want) {
console.log('FormExtensionAbility onAcquireFormState, want:' + want);
return formInfo.FormState.UNKNOWN;
}
}
};
```
## onShareForm
......@@ -270,14 +296,16 @@ Called by the widget provider to receive shared widget data.
**Example**
```ts
class MyFormExtensionAbility extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm(formId) {
console.log('FormExtensionAbility onShareForm, formId:' + formId);
let wantParams = {
"temperature":"20",
"time":"2022-8-8 09:59",
"temperature": "20",
"time": "2022-8-8 09:59",
};
return wantParams;
}
}
};
```
# @ohos.app.form.formHost
# @ohos.app.form.formHost (formHost)
The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status.
The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status.
> **NOTE**
>
......@@ -28,31 +28,32 @@ Deletes a widget. After this API is called, the application can no longer use th
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is deleted, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.deleteForm(formId, (error, data) => {
let formId = "12400633174999288";
formHost.deleteForm(formId, (error) => {
if (error) {
console.log('formHost deleteForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost deleteForm success');
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
## deleteForm
......@@ -82,21 +83,23 @@ Deletes a widget. After this API is called, the application can no longer use th
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Parameters**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
let formId = "12400633174999288";
formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success');
}).catch((error) => {
console.log('formHost deleteForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -115,27 +118,29 @@ Releases a widget. After this API is called, the application can no longer use t
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.releaseForm(formId, (error, data) => {
let formId = "12400633174999288";
formHost.releaseForm(formId, (error) => {
if (error) {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -155,27 +160,29 @@ Releases a widget. After this API is called, the application can no longer use t
| -------------- | ------ | ---- | ----------- |
| formId | string | Yes | Widget ID. |
| isReleaseCache | boolean | Yes | Whether to release the cache.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.releaseForm(formId, true, (error, data) => {
let formId = "12400633174999288";
formHost.releaseForm(formId, true, (error) => {
if (error) {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -206,21 +213,23 @@ Releases a widget. After this API is called, the application can no longer use t
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
let formId = "12400633174999288";
formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success');
}).catch((error) => {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -239,27 +248,29 @@ Requests a widget update. This API uses an asynchronous callback to return the r
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is updated, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.requestForm(formId, (error, data) => {
let formId = "12400633174999288";
formHost.requestForm(formId, (error) => {
if (error) {
console.log('formHost requestForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -289,21 +300,23 @@ Requests a widget update. This API uses a promise to return the result.
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
let formId = "12400633174999288";
formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success');
}).catch((error) => {
console.log('formHost requestForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -323,27 +336,29 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.castToNormalForm(formId, (error, data) => {
let formId = "12400633174999288";
formHost.castToNormalForm(formId, (error) => {
if (error) {
console.log('formHost castTempForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -373,21 +388,23 @@ Converts a temporary widget to a normal one. This API uses a promise to return t
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
let formId = "12400633174999288";
formHost.castToNormalForm(formId).then(() => {
console.log('formHost castTempForm success');
}).catch((error) => {
console.log('formHost castTempForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -406,27 +423,29 @@ Instructs the widget framework to make a widget visible. After this API is calle
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId, (error, data) => {
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId, (error) => {
if (error) {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -456,21 +475,23 @@ Instructs the widget framework to make a widget visible. After this API is calle
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success');
}).catch((error) => {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -489,27 +510,29 @@ Instructs the widget framework to make a widget invisible. After this API is cal
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId, (error, data) => {
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId, (error) => {
if (error) {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -539,21 +562,23 @@ Instructs the widget framework to make a widget invisible. After this API is cal
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success');
}).catch((error) => {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -572,27 +597,29 @@ Instructs the widget framework to make a widget updatable. After this API is cal
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId, (error, data) => {
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId, (error) => {
if (error) {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -622,21 +649,23 @@ Instructs the widget framework to make a widget updatable. After this API is cal
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success');
}).catch((error) => {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -655,27 +684,29 @@ Instructs the widget framework to make a widget not updatable. After this API is
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId, (error, data) => {
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId, (error) => {
if (error) {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -705,21 +736,23 @@ Instructs the widget framework to make a widget not updatable. After this API is
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = ["12400633174999288"];
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success');
}).catch((error) => {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -735,20 +768,21 @@ Checks whether the system is ready. This API uses an asynchronous callback to re
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.isSystemReady((error, data) => {
if (error) {
console.log('formHost isSystemReady, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -769,15 +803,16 @@ Checks whether the system is ready. This API uses a promise to return the result
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formId = "12400633174999288";
formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success');
}).catch((error) => {
console.log('formHost isSystemReady, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -795,21 +830,23 @@ Obtains the widget information provided by all applications on the device. This
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
formHost.getAllFormsInfo((error, data) => {
if (error) {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -826,20 +863,22 @@ Obtains the widget information provided by all applications on the device. This
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
| :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
formHost.getAllFormsInfo().then((data) => {
console.log('formHost getAllFormsInfo data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -858,28 +897,30 @@ Obtains the widget information provided by a given application on the device. Th
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => {
if (error) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -899,28 +940,30 @@ Obtains the widget information provided by a given application on the device. Th
| ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.|
| moduleName | string | Yes| Module name.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => {
if (error) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -944,27 +987,29 @@ Obtains the widget information provided by a given application on the device. Th
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
| :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -983,22 +1028,24 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of valid widget IDs.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formIds = new Array("12400633174999288", "12400633174999289");
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds, (error, data) => {
if (error) {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1027,15 +1074,17 @@ Deletes invalid widgets from the list. This API uses a promise to return the res
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
try {
var formIds = new Array("12400633174999288", "12400633174999289");
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1053,20 +1102,22 @@ Obtains the widget state. This API uses an asynchronous callback to return the r
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.|
| callback | AsyncCallback&lt;[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.|
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.|
| callback | AsyncCallback&lt;[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var want = {
import formHost from '@ohos.app.form.formHost';
let want = {
"deviceId": "",
"bundleName": "ohos.samples.FormApplication",
"abilityName": "FormAbility",
......@@ -1079,13 +1130,13 @@ var want = {
try {
formHost.acquireFormState(want, (error, data) => {
if (error) {
console.log('formHost acquireFormState, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1103,25 +1154,27 @@ Obtains the widget state. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.|
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.|
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise used to return the widget state obtained.|
| Promise&lt;[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise used to return the widget state obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var want = {
import formHost from '@ohos.app.form.formHost';
let want = {
"deviceId": "",
"bundleName": "ohos.samples.FormApplication",
"abilityName": "FormAbility",
......@@ -1135,10 +1188,10 @@ try {
formHost.acquireFormState(want).then((data) => {
console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost acquireFormState, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1160,6 +1213,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId);
}
......@@ -1179,11 +1234,13 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.|
| callback | Callback&lt;string&gt; | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.|
| callback | Callback&lt;string&gt; | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.<br> The value must be the same as that in **on("formUninstall")**.|
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId);
}
......@@ -1206,27 +1263,29 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| isVisible | boolean | Yes | Whether to make the widgets visible.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsVisible(formIds, true, (error, data) => {
formHost.notifyFormsVisible(formIds, true, (error) => {
if (error) {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1257,21 +1316,23 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success');
}).catch((error) => {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1291,27 +1352,29 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => {
formHost.notifyFormsEnableUpdate(formIds, true, (error) => {
if (error) {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1342,21 +1405,23 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
## shareForm
......@@ -1375,29 +1440,30 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| deviceId | string | Yes | Remote device ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
import formHost from '@ohos.app.form.formHost';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try {
formHost.shareForm(formId, deviceId, (error, data) => {
formHost.shareForm(formId, deviceId, (error) => {
if (error) {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1428,22 +1494,24 @@ Shares a specified widget with a remote device. This API uses a promise to retur
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Parameters**
**Example**
```ts
var formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
import formHost from '@ohos.app.form.formHost';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try {
formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success');
}).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -1451,6 +1519,8 @@ try {
notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callback: AsyncCallback\<void>): void
Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM
**System capability**: SystemCapability.Ability.Form
......@@ -1459,20 +1529,75 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| deviceId | string | Yes | Remote device ID.|
| formIds | Array\<string\> | Yes | ID of the widgets.|
| isProtected | boolean | Yes | Whether privacy protection is enabled.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If privacy protection is set successfully, **error** is undefined; otherwise, **error** is an error object.|
**Error codes**
| Error Code ID | Error Message |
| ------------------------------------------------------------ | ------------------ |
| 401 | Incorrect input parameter.|
| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |
**Example**
```ts
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsPrivacyProtected(formIds, true, (error) => {
if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
## notifyFormsPrivacyProtected
function notifyFormsPrivacyProtected(formIds: Array\<string\>, isProtected: boolean): Promise\<void\>;
Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------- | ---- | -------------------------------- |
| formIds | Array\<string\> | Yes | ID of the widgets.|
| isProtected | boolean | Yes | Whether privacy protection is enabled. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
| Error Code ID | Error Message |
| ------------------------------------------------------------ | ------------------ |
| 401 | Incorrect input parameter.|
| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.app.form.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost shareForm success');
console.log('formHost notifyFormsPrivacyProtected success');
}).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.log(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
<!--no_check-->
\ No newline at end of file
# @ohos.app.form.formInfo
# @ohos.app.form.formInfo (formInfo)
The **FormInfo** module provides widget information and state.
The **formInfo** module provides types and enums related to the widget information and state.
> **NOTE**
>
......@@ -30,11 +30,11 @@ Describes widget information.
| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. |
| isDefault | boolean | Yes | No | Whether the widget is the default one. |
| updateEnabled | boolean | Yes | No | Whether the widget is updatable. |
| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. |
| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. |
| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. |
| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. |
| formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. |
| updateDuration | string | Yes | No | Update period of the widget.|
| updateDuration | number | Yes | No | Update period of the widget.|
| defaultDimension | number | Yes | No | Default dimension of the widget. |
| supportDimensions | Array&lt;number&gt; | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). |
| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. |
......@@ -101,7 +101,7 @@ Enumerates the widget parameters.
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID.<br>**System API**: This is a system API. |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID. |
| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.|
## FormDimension
......@@ -125,9 +125,9 @@ Defines the widget information filter. Only the widget information that meets th
**System capability**: SystemCapability.Ability.Form
| Name | Description |
| ----------- | ------------ |
| moduleName | Only the information about the widget whose **moduleName** is the same as the provided value is returned.|
| Name | Type | Description |
| ----------- | ---- | ------------ |
| moduleName | string | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.<br>If this parameter is not set, **moduleName** is not used for filtering. |
## VisibilityType
......
# @ohos.app.form.formProvider
# @ohos.app.form.formProvider (formProvider)
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release.
......@@ -31,23 +31,25 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try {
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log(`formProvider setFormNextRefreshTime success`);
}
});
} catch (error) {
console.log("error" + JSON.stringify(error))
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -76,21 +78,23 @@ Sets the next refresh time for a widget. This API uses a promise to return the r
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try {
formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log('formProvider setFormNextRefreshTime success');
console.log(`formProvider setFormNextRefreshTime success`);
}).catch((error) => {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -114,25 +118,27 @@ Updates a widget. This API uses an asynchronous callback to return the result.
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try {
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj, (error, data) => {
if (error) {
console.log('formProvider updateForm, error:' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log(`formProvider updateForm success`);
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -161,23 +167,25 @@ Updates a widget. This API uses a promise to return the result.
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" });
try {
formProvider.updateForm(formId, obj).then(() => {
console.log('formProvider updateForm success');
console.log(`formProvider updateForm success`);
}).catch((error) => {
console.log('formProvider updateForm, error:' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -193,29 +201,31 @@ Obtains the application's widget information on the device. This API uses an asy
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formProvider from '@ohos.app.form.formProvider';
try {
formProvider.getFormsInfo((error, data) => {
if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data));
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
## getFormsInfo
......@@ -231,33 +241,35 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formInfo from '@ohos.application.formInfo';
const filter : formInfo.FormInfoFilter = {
import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter: formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName : "entry"
moduleName: "entry"
};
try {
formProvider.getFormsInfo(filter, (error, data) => {
if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data));
}
});
} catch(error) {
console.log(`catch err->${JSON.stringify(error)}`);
} catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -279,31 +291,33 @@ Obtains the application's widget information on the device. This API uses a prom
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formInfo from '@ohos.application.formInfo';
const filter : formInfo.FormInfoFilter = {
import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter: formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName : "entry"
moduleName: "entry"
};
try {
formProvider.getFormsInfo(filter).then((data) => {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -322,21 +336,23 @@ Requests to publish a widget carrying data to the widget host. This API uses an
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Error codes**
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
import formBindingData from '@ohos.application.formBindingData';
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -345,16 +361,16 @@ var want = {
}
};
try {
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" });
formProvider.requestPublishForm(want, obj, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -379,13 +395,15 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -396,15 +414,14 @@ var want = {
try {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
## requestPublishForm
......@@ -422,7 +439,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Name | Type | Mandatory| Description |
| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. |
| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. |
**Return value**
......@@ -434,13 +451,15 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Error Code ID| Error Message|
| -------- | -------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).
| 401 | Incorrect input parameter.|
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example**
```ts
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -452,10 +471,10 @@ try {
formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -478,10 +497,12 @@ Checks whether a widget can be published to the widget host. This API uses an as
**Example**
```ts
import formProvider from '@ohos.app.form.formProvider';
try {
formProvider.isRequestPublishFormSupported((error, isSupported) => {
if (error) {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
if (isSupported) {
var want = {
......@@ -495,20 +516,19 @@ try {
try {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
}
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
}
}
});
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
......@@ -531,6 +551,8 @@ Checks whether a widget can be published to the widget host. This API uses a pro
**Example**
```ts
import formProvider from '@ohos.app.form.formProvider';
try {
formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) {
......@@ -546,19 +568,16 @@ try {
formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
}
}).catch((error) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
console.log(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
console.log(`catch err->${JSON.stringify(error)}`);
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
<!--no_check-->
\ No newline at end of file
# appControl
# @ohos.bundle.appControl (appControl)
The **appControl** module provides APIs for setting, obtaining, and deleting the disposed status of an application. An application in the disposed state is forbidden to run. When a user clicks the application icon on the home screen, the corresponding page is displayed based on the disposal intent.
......
# @ohos.application.Ability
# @ohos.application.Ability (Ability)
The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
......@@ -15,7 +15,7 @@ This module provides the following common ability-related functions:
## Modules to Import
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
```
## Attributes
......@@ -47,7 +47,7 @@ Called to initialize the service logic when an ability is created.
**Example**
```ts
class myAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, param) {
console.log('onCreate, want:' + want.abilityName);
}
......@@ -67,7 +67,7 @@ Called when a **WindowStage** is created for this ability.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
......@@ -111,7 +111,7 @@ Called when the **WindowStage** is restored during the migration of this ability
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
......@@ -219,23 +219,24 @@ Called to save data during the ability migration preparation process.
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;
Called when the ability startup mode is set to singleton.
Called when a new Want is passed in and this UIAbility is started again.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want parameters, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
**Example**
```ts
class myAbility extends Ability {
onNewWant(want) {
onNewWant(want, launchParams) {
console.log('onNewWant, want:' + want.abilityName);
console.log('onNewWant, launchParams:' + JSON.stringify(launchParams));
}
}
```
......@@ -388,8 +389,9 @@ Sends sequenceable data to the target ability.
**Example**
```ts
import Ability from '@ohos.application.Ability';
class MyMessageAble{ // Custom sequenceable data structure
import UIAbility from '@ohos.app.ability.UIAbility';
class MyMessageAble{ // Custom sequenceable data structure.
name:""
str:""
num: 1
......@@ -412,11 +414,11 @@ Sends sequenceable data to the target ability.
};
var method = 'call_Function'; // Notification message string negotiated by the two abilities
var caller;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -472,7 +474,8 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
**Example**
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
class MyMessageAble{
name:""
str:""
......@@ -496,11 +499,11 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
};
var method = 'call_Function';
var caller;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -543,14 +546,17 @@ Releases the caller interface of the target ability.
**Example**
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
var caller;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -585,13 +591,15 @@ Registers a callback that is invoked when the stub on the target ability is disc
**Example**
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
var caller;
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -642,7 +650,7 @@ Registers a caller notification callback, which is invoked when the target abili
**Example**
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
class MyMessageAble{
name:""
str:""
......@@ -671,7 +679,7 @@ Registers a caller notification callback, which is invoked when the target abili
pdata.readSequenceable(msg);
return new MyMessageAble("test1", "Callee test");
}
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log('Callee onCreate is called');
try {
......@@ -710,9 +718,11 @@ Deregisters a caller notification callback, which is invoked when the target abi
**Example**
```ts
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
var method = 'call_Function';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log('Callee onCreate is called');
try {
......
# @ohos.application.AbilityConstant
# @ohos.application.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**
>
> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. 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
......@@ -21,12 +19,12 @@ import AbilityConstant from '@ohos.application.AbilityConstant';
| 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.|
| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit.|
## AbilityConstant.LaunchReason
Enumerates ability launch reasons.
Enumerates the initial ability launch reasons.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -41,7 +39,7 @@ Enumerates ability launch reasons.
## AbilityConstant.LastExitReason
Enumerates reasons for the last exit.
Enumerates the reasons for the last exit.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -54,7 +52,7 @@ Enumerates reasons for the last exit.
## AbilityConstant.OnContinueResult
Enumerates ability continuation results.
Enumerates the ability continuation results.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
# @ohos.application.abilityDelegatorRegistry
# @ohos.application.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.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......
# @ohos.application.AbilityLifecycleCallback
# @ohos.application.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 provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. These callbacks can be used as an input parameter of [registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback).
> **NOTE**
>
> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. 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.
......@@ -25,9 +25,9 @@ Called when an ability is created.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onWindowStageCreate
......@@ -40,10 +40,10 @@ Called when the window stage of an ability is created.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](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 | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageActive
......@@ -56,10 +56,10 @@ Called when the window stage of an ability gains focus.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](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 | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageInactive
......@@ -72,10 +72,10 @@ Called when the window stage of an ability loses focus.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](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 | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onWindowStageDestroy
......@@ -88,10 +88,10 @@ Called when the window stage of an ability is destroyed.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](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 | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.|
## AbilityLifecycleCallback.onAbilityDestroy
......@@ -104,9 +104,9 @@ Called when an ability is destroyed.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityForeground
......@@ -119,9 +119,9 @@ Called when an ability is switched from the background to the foreground.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityBackground
......@@ -134,9 +134,9 @@ Called when an ability is switched from the foreground to the background.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
## AbilityLifecycleCallback.onAbilityContinue
......@@ -149,63 +149,63 @@ Called when an ability is continued on another device.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.|
**Example**
```ts
import AbilityStage from "@ohos.application.AbilityStage";
var lifecycleid;
var lifecycleId;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
let AbilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
onAbilityCreate(ability) {
console.log("onAbilityCreate ability:" + JSON.stringify(ability));
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
onWindowStageCreate(ability, windowStage) {
console.log("onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));
onWindowStageActive(ability, windowStage) {
console.log("onWindowStageActive ability:" + JSON.stringify(ability));
console.log("onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
onWindowStageInactive(ability, windowStage) {
console.log("onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
onWindowStageDestroy(ability, windowStage) {
console.log("onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
onAbilityDestroy(ability) {
console.log("onAbilityDestroy ability:" + JSON.stringify(ability));
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
onAbilityForeground(ability) {
console.log("onAbilityForeground ability:" + JSON.stringify(ability));
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
onAbilityBackground(ability) {
console.log("onAbilityBackground ability:" + JSON.stringify(ability));
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
onAbilityContinue(ability) {
console.log("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.
lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId));
}
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
}
......
# @ohos.application.abilityManager
# @ohos.application.abilityManager (AbilityManager)
The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import
```ts
import AbilityManager from '@ohos.application.abilityManager'
import abilityManager from '@ohos.application.abilityManager'
```
## AbilityState
......@@ -26,8 +26,8 @@ Enumerates the ability states.
| 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
......@@ -49,13 +49,11 @@ Updates the configuration. This API uses an asynchronous callback to return the
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config, () => {
abilityManager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
```
......@@ -85,13 +83,11 @@ Updates the configuration. This API uses a promise to return the result.
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config).then(() => {
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
......@@ -112,14 +108,12 @@ 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 result. |
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
abilityManager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
......@@ -138,14 +132,12 @@ 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)>> | Promise used to return the result.|
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos().then((data) => {
abilityManager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
......@@ -167,16 +159,14 @@ 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. |
| callback | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | Yes | Callback used to return the result. |
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
......@@ -201,16 +191,14 @@ Obtains the extension running information. This API uses a promise to return the
| 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 result.|
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => {
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
......@@ -229,14 +217,12 @@ 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 result. |
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility((err,data) => {
abilityManager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
});
```
......@@ -253,14 +239,12 @@ 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 result.|
**Example**
```ts
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility().then((data) => {
abilityManager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
......
# @ohos.application.AbilityStage
# @ohos.application.AbilityStage (AbilityStage)
**AbilityStage** is a runtime class for HAP files.
......@@ -38,21 +38,21 @@ Called when the application is created.
onAcceptWant(want: Want): string;
Called when a specified ability is started.
Called when a UIAbility is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-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-application-want.md) | Yes| Want information about the target UIAbility, such as the ability name and bundle name.|
**Return value**
| Type| Description|
| -------- | -------- |
| string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.|
| Type| Description|
| -------- | -------- |
| string | Returns a UIAbility ID. If this UIAbility has been started, no new instance is created and the UIAbility is placed at the top of the stack. Otherwise, a new instance is created and started.|
**Example**
......@@ -76,9 +76,9 @@ Called when the global configuration is updated.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.|
**Example**
......@@ -100,9 +100,9 @@ Called when the system has decided to adjust the memory level. For example, this
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-application-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-application-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.|
**Example**
......@@ -118,10 +118,10 @@ Called when the system has decided to adjust the memory level. For example, this
context: AbilityStageContext;
Describes the configuration information about the context.
Defines the **Context** object 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) | **Context** object of AbilityStage.|
# @ohos.application.appManager
# @ohos.application.appManager (appManager)
The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process.
......@@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API
## Modules to Import
```ts
import app from '@ohos.application.appManager';
import appManager from '@ohos.application.appManager';
```
## appManager.isRunningInStabilityTest<sup>8+</sup>
......@@ -29,9 +29,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Example**
```ts
import app from '@ohos.application.appManager';
app.isRunningInStabilityTest((err, flag) => {
console.log('startAbility result:' + JSON.stringify(err));
appManager.isRunningInStabilityTest((err, flag) => {
console.log('error:' + JSON.stringfy(err));
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
})
```
......@@ -53,11 +53,10 @@ Checks whether this application is undergoing a stability test. This API uses a
**Example**
```ts
import app from '@ohos.application.appManager';
app.isRunningInStabilityTest().then((flag) => {
console.log('success:' + JSON.stringify(flag));
appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
console.log('error:' + JSON.stringify(error));
});
```
......@@ -79,10 +78,10 @@ Checks whether this application is running on a RAM constrained device. This API
**Example**
```ts
app.isRamConstrainedDevice().then((data) => {
console.log('success:' + JSON.stringify(data));
appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
console.log('error:' + JSON.stringify(error));
});
```
......@@ -103,9 +102,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Example**
```ts
app.isRamConstrainedDevice((err, data) => {
console.log('startAbility result failed:' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
appManager.isRamConstrainedDevice((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
})
```
......@@ -126,10 +125,10 @@ Obtains the memory size of this application. This API uses a promise to return t
**Example**
```ts
app.getAppMemorySize().then((data) => {
console.log('success:' + JSON.stringify(data));
appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
console.log('error:' + JSON.stringify(error));
});
```
......@@ -150,9 +149,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Example**
```ts
app.getAppMemorySize((err, data) => {
console.log('startAbility result failed :' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
appManager.getAppMemorySize((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The size of app memory is:' + JSON.stringify(data));
})
```
## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
......@@ -171,15 +170,15 @@ Obtains information about the running processes. This API uses a promise to retu
| Type| Description|
| -------- | -------- |
| Promise\<Array\<ProcessRunningInfo>> | Promise used to return the process information.|
| Promise\<Array\<[ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)>> | Promise used to return the process information.|
**Example**
```ts
app.getProcessRunningInfos().then((data) => {
console.log('success:' + JSON.stringify(data));
appManager.getProcessRunningInfos().then((data) => {
console.log('The process running infos is:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
console.log('error:' + JSON.stringify(error));
});
```
......@@ -199,14 +198,14 @@ Obtains information about the running processes. This API uses an asynchronous c
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<ProcessRunningInfo>> | Yes| Obtains information about the running processes. This API uses a promise to return the result.|
| callback | AsyncCallback\<Array\<[ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)>> | Yes| Obtains information about the running processes. This API uses a promise to return the result.|
**Example**
```ts
app.getProcessRunningInfos((err, data) => {
console.log('startAbility result failed :' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
appManager.getProcessRunningInfos((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The process running infos is:' + JSON.stringify(data));
})
```
......@@ -229,10 +228,10 @@ Obtains information about the running processes. This API uses a promise to retu
**Example**
```ts
app.getProcessRunningInformation().then((data) => {
console.log('success:' + JSON.stringify(data));
appManager.getProcessRunningInformation().then((data) => {
console.log('The process running info is:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
console.log('error:' + JSON.stringify(error));
});
```
......@@ -255,9 +254,9 @@ Obtains information about the running processes. This API uses an asynchronous c
**Example**
```ts
app.getProcessRunningInformation((err, data) => {
console.log('startAbility result failed :' + JSON.stringify(err));
console.log('startAbility result success:' + JSON.stringify(data));
appManager.getProcessRunningInformation((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The process running info is:' + JSON.stringify(data));
})
```
......@@ -299,7 +298,7 @@ Registers an observer to listen for the state changes of all applications.
console.log('------------ onProcessStateChanged -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
```
......@@ -343,7 +342,7 @@ Registers an observer to listen for the state changes of a specified application
}
}
var bundleNameList = ['bundleName1', 'bundleName2'];
const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList);
const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList);
console.log('-------- observerCode: ---------', observerCode);
```
## appManager.unregisterApplicationStateObserver<sup>8+</sup>
......@@ -375,7 +374,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
console.log('------------ unregisterApplicationStateObserverCallback ------------', err);
}
}
app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback);
appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback);
```
## appManager.unregisterApplicationStateObserver<sup>8+</sup>
......@@ -407,7 +406,7 @@ Deregisters the application state observer. This API uses a promise to return th
```ts
var observerId = 100;
app.unregisterApplicationStateObserver(observerId)
appManager.unregisterApplicationStateObserver(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
......@@ -420,7 +419,7 @@ Deregisters the application state observer. This API uses a promise to return th
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result.
Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -432,7 +431,7 @@ Obtains applications that are running in the foreground. This API uses an asynch
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<AppStateData>> | Yes| Callback used to return the application state data.|
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Yes| Callback used to return the application information.|
**Example**
......@@ -444,14 +443,14 @@ Obtains applications that are running in the foreground. This API uses an asynch
console.log('--------- getForegroundApplicationsCallback success ---------', data)
}
}
app.getForegroundApplications(getForegroundApplicationsCallback);
appManager.getForegroundApplications(getForegroundApplicationsCallback);
```
## appManager.getForegroundApplications<sup>8+</sup>
getForegroundApplications(): Promise\<Array\<AppStateData>>;
Obtains applications that are running in the foreground. This API uses a promise to return the result.
Obtains information about the applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO
......@@ -463,12 +462,12 @@ Obtains applications that are running in the foreground. This API uses a promise
| Type| Description|
| -------- | -------- |
| Promise\<Array\<ProcessRunningInfo>> | Promise used to return the application state data.|
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return the application information.|
**Example**
```ts
app.getForegroundApplications()
appManager.getForegroundApplications()
.then((data) => {
console.log('--------- getForegroundApplications success -------', data);
})
......@@ -483,7 +482,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
Kills a process by bundle name and account ID. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -491,17 +490,17 @@ Kills a process by bundle name and account ID. This API uses a promise to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
**Example**
```ts
var bundleName = 'bundleName';
var accountId = 0;
app.killProcessWithAccount(bundleName, accountId)
appManager.killProcessWithAccount(bundleName, accountId)
.then((data) => {
console.log('------------ killProcessWithAccount success ------------', data);
})
......@@ -521,15 +520,15 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Example**
......@@ -543,7 +542,7 @@ function killProcessWithAccountCallback(err, data) {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
}
}
app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
```
## appManager.killProcessesByBundleName<sup>8+</sup>
......@@ -562,7 +561,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
......@@ -576,7 +575,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
}
}
app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
```
## appManager.killProcessesByBundleName<sup>8+</sup>
......@@ -595,7 +594,7 @@ Kills a process by bundle name. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
**Return value**
......@@ -606,8 +605,8 @@ Kills a process by bundle name. This API uses a promise to return the result.
**Example**
```ts
var bundleName = 'bundleName';
app.killProcessesByBundleName(bundleName)
var bundleName = 'com.example.myapplication';
appManager.killProcessesByBundleName(bundleName)
.then((data) => {
console.log('------------ killProcessesByBundleName success ------------', data);
})
......@@ -632,7 +631,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
......@@ -646,7 +645,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
}
}
app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
```
## appManager.clearUpApplicationData<sup>8+</sup>
......@@ -665,7 +664,7 @@ Clears application data by bundle name. This API uses a promise to return the re
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.|
| bundleName | string | Yes| Bundle name.|
**Return value**
......@@ -677,7 +676,7 @@ Clears application data by bundle name. This API uses a promise to return the re
```ts
var bundleName = 'bundleName';
app.clearUpApplicationData(bundleName)
appManager.clearUpApplicationData(bundleName)
.then((data) => {
console.log('------------ clearUpApplicationData success ------------', data);
})
......
# @ohos.application.Configuration
# @ohos.application.Configuration (Configuration)
The **Configuration** module defines environment change information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead.
......
# @ohos.application.ConfigurationConstant
# @ohos.application.ConfigurationConstant (ConfigurationConstant)
The **ConfigurationConstant** module provides the enumerated values of the environment configuration information.
......
# @ohos.application.context
# @ohos.application.context (Context)
The **Context** module provides all level-2 module APIs for developers to export.
......
# @ohos.application.EnvironmentCallback
# @ohos.application.EnvironmentCallback (EnvironmentCallback)
The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes.
The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated** and **onMemoryLevel**, for the application context to listen for system environment changes.
> **NOTE**
>
> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. 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.
......@@ -25,18 +25,32 @@ Called when the system environment changes.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.|
## EnvironmentCallback.onMemoryLevel
onMemoryLevel(level: number): void;
Called when the system memory level changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.|
**Example**
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from '@ohos.app.ability.UIAbility';
var callbackId;
export default class MyAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
......@@ -44,6 +58,9 @@ export default class MyAbility extends Ability {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
onMemoryLevel(level){
console.log("onMemoryLevel level:" + level);
}
}
// 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext;
......
# @ohos.application.errorManager (Error Manager)
# @ohos.application.errorManager (ErrorManager)
The **errorManager** module provides APIs for registering and deregistering error observers.
The **ErrorManager** module provides APIs for registering and deregistering error observers.
> **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 are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
......
# @ohos.application.ExtensionAbility
# @ohos.application.ExtensionAbility (ExtensionAbility)
The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information.
The **ExtensionAbility** module manages the ExtensionAbility lifecycle and context, such as creating and destroying an ExtensionAbility, and dumping client information.
> **NOTE**
>
......
# @ohos.application.formBindingData
# @ohos.application.formBindingData (formBindingData)
The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information.
......@@ -48,16 +48,17 @@ Creates a **FormBindingData** object.
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
context.getOrCreateLocalDir((err,data)=>{
let path=data+"/xxx.jpg";
let fd = fileio.openSync(path);
import formBindingData from @ohos.application.formBindingData;
import fs from '@ohos.file.fs';
try {
let fd = fs.openSync('/path/to/form.png')
let obj = {
"temperature": "21°",
"formImages": {"image": fd}
"formImages": { "image": fd }
};
let formBindingDataObj = formBindingData.createFormBindingData(obj);
})
formBindingData.createFormBindingData(obj);
} catch (error.code) {
console.log('catch error, error:' + JSON.stringify(error));
}
```
# @ohos.application.formError
# @ohos.application.formError (formError)
The **FormError** module provides error codes for widgets.
The **formError** module provides error codes for widgets.
> **NOTE**
>
......@@ -50,5 +50,3 @@ SystemCapability.Ability.Form
| ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. |
| ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. |
| ERR_DISTRIBUTED_SCHEDULE_FAILED<sup>9+</sup> | 37 | The distributed scheduler failed.<br>**System API**: This is a system API. |
<!--no_check-->
\ No newline at end of file
# @ohos.application.FormExtension
# @ohos.application.FormExtension (FormExtension)
The **FormExtension** module provides APIs related to Form Extension abilities.
......
# @ohos.application.formHost
# @ohos.application.formHost (formHost)
The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status.
The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> This module is deprecated since API version 9. You are advised to use [FormHost](js-apis-app-form-formHost.md) instead.
> This module is deprecated since API version 9. You are advised to use [formHost](js-apis-app-form-formHost.md) instead.
> The APIs provided by this module are system APIs.
## Modules to Import
......@@ -34,10 +34,12 @@ Deletes a widget. After this API is called, the application can no longer use th
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.deleteForm(formId, (error, data) => {
if (error.code) {
console.log('formHost deleteForm, error:' + JSON.stringify(error));
console.error('formHost deleteForm, error:' + JSON.stringify(error));
}
});
```
......@@ -67,11 +69,13 @@ Deletes a widget. After this API is called, the application can no longer use th
**Parameters**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success');
}).catch((error) => {
console.log('formHost deleteForm, error:' + JSON.stringify(error));
console.error('formHost deleteForm, error:' + JSON.stringify(error));
});
```
......@@ -95,10 +99,14 @@ Releases a widget. After this API is called, the application can no longer use t
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.releaseForm(formId, (error, data) => {
if (error.code) {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.error('formHost releaseForm, error:' + JSON.stringify(error));
} else {
console.log('formHost releaseForm success');
}
});
```
......@@ -124,10 +132,14 @@ Releases a widget. After this API is called, the application can no longer use t
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.releaseForm(formId, true, (error, data) => {
if (error.code) {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.error('formHost releaseForm, error:' + JSON.stringify(error));
} else {
console.log('formHost releaseForm success');
}
});
```
......@@ -158,11 +170,13 @@ Releases a widget. After this API is called, the application can no longer use t
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success');
}).catch((error) => {
console.log('formHost releaseForm, error:' + JSON.stringify(error));
console.error('formHost releaseForm, error:' + JSON.stringify(error));
});
```
......@@ -186,10 +200,12 @@ Requests a widget update. This API uses an asynchronous callback to return the r
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.requestForm(formId, (error, data) => {
if (error.code) {
console.log('formHost requestForm, error:' + JSON.stringify(error));
console.error('formHost requestForm, error:' + JSON.stringify(error));
}
});
```
......@@ -219,11 +235,13 @@ Requests a widget update. This API uses a promise to return the result.
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success');
}).catch((error) => {
console.log('formHost requestForm, error:' + JSON.stringify(error));
console.error('formHost requestForm, error:' + JSON.stringify(error));
});
```
......@@ -242,15 +260,17 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.castTempForm(formId, (error, data) => {
if (error.code) {
console.log('formHost castTempForm, error:' + JSON.stringify(error));
console.error('formHost castTempForm, error:' + JSON.stringify(error));
}
});
```
......@@ -280,11 +300,13 @@ Converts a temporary widget to a normal one. This API uses a promise to return t
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.castTempForm(formId).then(() => {
console.log('formHost castTempForm success');
}).catch((error) => {
console.log('formHost castTempForm, error:' + JSON.stringify(error));
console.error('formHost castTempForm, error:' + JSON.stringify(error));
});
```
......@@ -303,15 +325,17 @@ Instructs the widget framework to make a widget visible. After this API is calle
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId, (error, data) => {
if (error.code) {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error));
}
});
```
......@@ -341,11 +365,13 @@ Instructs the widget framework to make a widget visible. After this API is calle
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success');
}).catch((error) => {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error));
});
```
......@@ -364,15 +390,17 @@ Instructs the widget framework to make a widget invisible. After this API is cal
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId, (error, data) => {
if (error.code) {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
}
});
```
......@@ -402,11 +430,13 @@ Instructs the widget framework to make a widget invisible. After this API is cal
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success');
}).catch((error) => {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
});
```
......@@ -425,15 +455,17 @@ Instructs the widget framework to make a widget updatable. After this API is cal
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId, (error, data) => {
if (error.code) {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error));
}
});
```
......@@ -463,11 +495,13 @@ Instructs the widget framework to make a widget updatable. After this API is cal
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success');
}).catch((error) => {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error));
});
```
......@@ -486,15 +520,17 @@ Instructs the widget framework to make a widget not updatable. After this API is
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId, (error, data) => {
if (error.code) {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error));
}
});
```
......@@ -524,11 +560,13 @@ Instructs the widget framework to make a widget not updatable. After this API is
**Example**
```ts
var formId = ["12400633174999288"];
import formHost from '@ohos.application.formHost';
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success');
}).catch((error) => {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error));
});
```
......@@ -544,15 +582,17 @@ Checks whether the system is ready. This API uses an asynchronous callback to re
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.isSystemReady((error, data) => {
if (error.code) {
console.log('formHost isSystemReady, error:' + JSON.stringify(error));
console.error('formHost isSystemReady, error:' + JSON.stringify(error));
}
});
```
......@@ -574,11 +614,13 @@ Checks whether the system is ready. This API uses a promise to return the result
**Example**
```ts
var formId = "12400633174999288";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success');
}).catch((error) => {
console.log('formHost isSystemReady, error:' + JSON.stringify(error));
console.error('formHost isSystemReady, error:' + JSON.stringify(error));
});
```
......@@ -596,14 +638,16 @@ Obtains the widget information provided by all applications on the device. This
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
formHost.getAllFormsInfo((error, data) => {
if (error.code) {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data));
}
......@@ -624,15 +668,17 @@ Obtains the widget information provided by all applications on the device. This
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
formHost.getAllFormsInfo().then((data) => {
console.log('formHost getAllFormsInfo data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error));
});
```
......@@ -651,14 +697,16 @@ Obtains the widget information provided by a given application on the device. Th
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => {
if (error.code) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.error('formHost getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}
......@@ -681,14 +729,16 @@ Obtains the widget information provided by a given application on the device. Th
| ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.|
| moduleName | string | Yes| Module name.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => {
if (error.code) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.error('formHost getFormsInfo, error:' + JSON.stringify(error));
} else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}
......@@ -716,15 +766,17 @@ Obtains the widget information provided by a given application on the device. Th
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
console.error('formHost getFormsInfo, error:' + JSON.stringify(error));
});
```
......@@ -743,15 +795,17 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of valid widget IDs.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds, (error, data) => {
if (error.code) {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error));
} else {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}
......@@ -783,11 +837,13 @@ Deletes invalid widgets from the list. This API uses a promise to return the res
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error));
});
```
......@@ -805,13 +861,15 @@ Obtains the widget state. This API uses an asynchronous callback to return the r
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.|
| callback | AsyncCallback&lt;[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)&gt; | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.|
| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.|
| callback | AsyncCallback&lt;[formInfo.FormStateInfo](js-apis-application-formInfo.md#formstateinfo)&gt; | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.|
**Example**
```ts
var want = {
import formHost from '@ohos.application.formHost';
let want = {
"deviceId": "",
"bundleName": "ohos.samples.FormApplication",
"abilityName": "FormAbility",
......@@ -823,7 +881,7 @@ var want = {
};
formHost.acquireFormState(want, (error, data) => {
if (error.code) {
console.log('formHost acquireFormState, error:' + JSON.stringify(error));
console.error('formHost acquireFormState, error:' + JSON.stringify(error));
} else {
console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}
......@@ -855,7 +913,9 @@ Obtains the widget state. This API uses a promise to return the result.
**Example**
```ts
var want = {
import formHost from '@ohos.application.formHost';
let want = {
"deviceId": "",
"bundleName": "ohos.samples.FormApplication",
"abilityName": "FormAbility",
......@@ -868,7 +928,7 @@ var want = {
formHost.acquireFormState(want).then((data) => {
console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}).catch((error) => {
console.log('formHost acquireFormState, error:' + JSON.stringify(error));
console.error('formHost acquireFormState, error:' + JSON.stringify(error));
});
```
......@@ -890,6 +950,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to
**Example**
```ts
import formHost from '@ohos.application.formHost';
let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId);
}
......@@ -909,11 +971,13 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.|
| callback | Callback&lt;string&gt; | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.|
| callback | Callback&lt;string&gt; | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.<br> The value must be the same as that in **on("formUninstall")**.|
**Example**
```ts
import formHost from '@ohos.application.formHost';
let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId);
}
......@@ -936,15 +1000,17 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| isVisible | boolean | Yes | Whether to make the widgets visible.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsVisible(formIds, true, (error, data) => {
if (error.code) {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error));
}
});
```
......@@ -975,11 +1041,13 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success');
}).catch((error) => {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error));
});
```
......@@ -999,15 +1067,17 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou
| ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | Yes | List of widget IDs.|
| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => {
if (error.code) {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
}
});
```
......@@ -1038,11 +1108,13 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r
**Example**
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
});
```
## shareForm<sup>9+</sup>
......@@ -1051,7 +1123,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;)
Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM
**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.Form
......@@ -1061,16 +1133,18 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca
| ------ | ------ | ---- | ------- |
| formId | string | Yes | Widget ID.|
| deviceId | string | Yes | Remote device ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is shared, **err** is undefined; otherwise, **err** is an error object.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.|
**Example**
```ts
var formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
formHost.shareForm(formId, deviceId, (error, data) => {
if (error.code) {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.error('formHost shareForm, error:' + JSON.stringify(error));
}
});
```
......@@ -1101,18 +1175,22 @@ Shares a specified widget with a remote device. This API uses a promise to retur
**Parameters**
```ts
var formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
import formHost from '@ohos.application.formHost';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success');
}).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.error('formHost shareForm, error:' + JSON.stringify(error));
});
```
## notifyFormsPrivacyProtected<sup>9+</sup>
notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callback: AsyncCallback\<void>): void
notifyFormsPrivacyProtected(formIds: Array&lt;string&gt;, isProtected: boolean, callback: AsyncCallback&lt;void&gt;): void
Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM
......@@ -1126,10 +1204,51 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb
| deviceId | string | Yes | Remote device ID.|
```ts
var formIds = new Array("12400633174999288", "12400633174999289");
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost shareForm success');
}).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error));
console.error('formHost shareForm, error:' + JSON.stringify(error));
});
```
## notifyFormsPrivacyProtected
function notifyFormsPrivacyProtected(formIds: Array&lt;string&gt;, isProtected: boolean): Promise&lt;void&gt;;
Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------- | ---- | -------------------------------- |
| formIds | Array&lt;string&gt; | Yes | ID of the widgets.|
| isProtected | boolean | Yes | Whether privacy protection is enabled. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
```ts
import formHost from '@ohos.application.formHost';
let formIds = new Array("12400633174999288", "12400633174999289");
try {
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost notifyFormsPrivacyProtected success');
}).catch((error) => {
console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error));
});
} catch(error) {
console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error));
}
```
# @ohos.application.formInfo
# @ohos.application.formInfo (formInfo)
The **FormInfo** module provides widget information and state.
The **formInfo** module provides types and enums related to the widget information and state.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> This module is deprecated since API version 9. You are advised to use [FormInfo](js-apis-app-form-formInfo.md) instead.
> This module is deprecated since API version 9. You are advised to use [formInfo](js-apis-app-form-formInfo.md) instead.
## Modules to Import
......@@ -31,11 +31,11 @@ Describes widget information.
| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. |
| isDefault | boolean | Yes | No | Whether the widget is the default one. |
| updateEnabled | boolean | Yes | No | Whether the widget is updatable. |
| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. |
| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. |
| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. |
| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. |
| formConfigAbility | string | Yes | No | Configuration ability of the widget. |
| updateDuration | string | Yes | No | Update period of the widget.|
| updateDuration | number | Yes | No | Update period of the widget.|
| defaultDimension | number | Yes | No | Default dimension of the widget. |
| supportDimensions | Array&lt;number&gt; | Yes | No | Dimensions supported by the widget. |
| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. |
......@@ -102,7 +102,7 @@ Enumerates the widget parameters.
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. |
| ABILITY_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY<sup>9+</sup> | "ohos.extra.param.key.device_id" | Device ID.<br>**System API**: This is a system API. |
| DEVICE_ID_KEY<sup>9+</sup> | "ohos.extra.param.key.device_id" | Device ID. |
| BUNDLE_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.|
## FormDimension<sup>9+</sup>
......@@ -119,17 +119,6 @@ Enumerates the widget dimensions.
| Dimension_4_4 <sup>9+</sup> | 4 | 4 x 4. |
| Dimension_2_1 <sup>9+</sup> | 5 | 2 x 1. |
## VisibilityType
Enumerates the visibility types of the widget.
**System capability**: SystemCapability.Ability.Form
| Name | Value | Description |
| ----------- | ---- | ------------ |
| FORM_VISIBLE<sup>9+<sup> | 1 | The card is visible. |
| FORM_INVISIBLE<sup>9+<sup> | 2 | The card is invisible.|
## FormInfoFilter<sup>9+</sup>
Defines the widget information filter. Only the widget information that meets the filter is returned.
......@@ -138,7 +127,7 @@ Defines the widget information filter. Only the widget information that meets th
| Name | Description |
| ----------- | ------------ |
| moduleName<sup>9+</sup> | Only the information about the widget whose **moduleName** is the same as the provided value is returned.|
| moduleName<sup>9+</sup> | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.<br>If this parameter is not set, **moduleName** is not used for filtering.|
## VisibilityType<sup>9+</sup>
......
# @ohos.application.formProvider
# @ohos.application.formProvider (formProvider)
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release.
> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> This module is deprecated since API version 9. You are advised to use [FormProvider](js-apis-app-form-formProvider.md) instead.
> This module is deprecated since API version 9. You are advised to use [formProvider](js-apis-app-form-formProvider.md) instead.
## Modules to Import
......@@ -31,7 +31,9 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback
**Example**
```ts
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error.code) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
......@@ -63,7 +65,9 @@ Sets the next refresh time for a widget. This API uses a promise to return the r
**Example**
```ts
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log('formProvider setFormNextRefreshTime success');
}).catch((error) => {
......@@ -84,14 +88,16 @@ Updates a widget. This API uses an asynchronous callback to return the result.
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.|
| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. |
| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj, (error, data) => {
if (error.code) {
......@@ -113,7 +119,7 @@ Updates a widget. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.|
| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdat) | Yes | Data to be used for the update. |
| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. |
**Return value**
......@@ -125,7 +131,9 @@ Updates a widget. This API uses a promise to return the result.
```ts
import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288";
import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj).then(() => {
console.log('formProvider updateForm success');
......@@ -146,11 +154,13 @@ Obtains the application's widget information on the device. This API uses an asy
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Example**
```ts
import formProvider from '@ohos.app.form.formProvider';
formProvider.getFormsInfo((error, data) => {
if (error.code) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
......@@ -172,12 +182,14 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Example**
```ts
import formInfo from '@ohos.application.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter : formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName : "entry"
......@@ -209,12 +221,14 @@ Obtains the application's widget information on the device. This API uses a prom
| Type | Description |
| :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Promise used to return the information obtained.|
| Promise&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Promise used to return the information obtained.|
**Example**
```ts
import formInfo from '@ohos.application.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter : formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName : "entry"
......@@ -241,14 +255,15 @@ Requests to publish a widget carrying data to the widget host. This API uses an
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Example**
```ts
import formBindingData from '@ohos.application.formBindingData';
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -286,7 +301,9 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c
**Example**
```ts
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -318,7 +335,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Name | Type | Mandatory| Description |
| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:<br>Information about the target widget.<br>**abilityName**: ability of the target widget.<br>**parameters**:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" |
| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | No | Data used for creating the widget. |
| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.|
**Return value**
......@@ -329,7 +346,9 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
**Example**
```ts
var want = {
import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -368,7 +387,7 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
} else {
if (isSupported) {
var want = {
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......@@ -409,7 +428,7 @@ Checks whether a widget can be published to the widget host. This API uses a pro
```ts
formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) {
var want = {
let want = {
abilityName: "FormAbility",
parameters: {
"ohos.extra.param.key.form_dimension": 2,
......
# @ohos.application.missionManager
# @ohos.application.missionManager (missionManager)
The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -32,13 +32,13 @@ Registers a listener to observe the mission status.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Listener to register.|
| listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.|
| number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.|
**Example**
......@@ -73,7 +73,7 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.|
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -113,7 +113,7 @@ Deregisters a mission status listener. This API uses a promise to return the res
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.|
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.|
**Return value**
......@@ -169,7 +169,12 @@ Obtains the information about a given mission. This API uses an asynchronous cal
var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);});
missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => {
console.log("getMissionInfo is called, error.code = " + error.code)
if (error.code) {
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("mission.missionId = " + mission.missionId);
console.log("mission.runningState = " + mission.runningState);
console.log("mission.lockedState = " + mission.lockedState);
......@@ -242,7 +247,11 @@ Obtains information about all missions. This API uses an asynchronous callback t
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
})
......@@ -311,13 +320,21 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getMissionSnapShot("", id, (error, snapshot) => {
console.log("getMissionSnapShot is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionSnapShot failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
......@@ -393,13 +410,21 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => {
console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code);
if (error.code) {
console.log("getLowResolutionMissionSnapShot failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
......@@ -475,7 +500,11 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
......@@ -554,7 +583,11 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
......@@ -637,7 +670,11 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
......@@ -768,7 +805,11 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
......@@ -806,7 +847,11 @@ Switches a given mission to the foreground, with the startup parameters for the
import missionManager from '@ohos.application.missionManager'
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
......
# @ohos.application.ServiceExtensionAbility
# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility)
The **ServiceExtensionAbility** module provides APIs for Service Extension abilities.
> **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 are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead.
>
> 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
......@@ -40,9 +43,9 @@ Called when a Service Extension ability is created to initialize the service log
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
**Example**
......@@ -88,10 +91,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.|
**Example**
......@@ -116,15 +119,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
**Return value**
| Type| Description|
| -------- | -------- |
| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.|
| Type| Description|
| -------- | -------- |
| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.|
**Example**
......@@ -158,9 +161,9 @@ Called when this Service Extension ability is disconnected.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
**Example**
......@@ -184,9 +187,9 @@ Called when this Service Extension ability is reconnected.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.|
**Example**
......@@ -210,9 +213,9 @@ Called when the configuration of this Service Extension ability is updated.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.|
**Example**
......@@ -236,9 +239,9 @@ Dumps the client information.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
......
# @ohos.application.StartOptions
# @ohos.application.StartOptions (StartOptions)
The **StartOptions** module implements ability startup options.
> **NOTE**
>
> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. 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
......
# @ohos.application.StaticSubscriberExtensionAbility
# @ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)
The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers.
> **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
......@@ -26,9 +27,10 @@ Callback of the common event of a static subscriber.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.|
| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.|
**Example**
```ts
var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility")
{
......
# @ohos.application.testRunner
# @ohos.application.testRunner (TestRunner)
The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases.
......
# @ohos.application.Want
# @ohos.application.Want (Want)
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility()** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -18,26 +18,26 @@ import Want from '@ohos.application.Want';
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. |
| bundleName | string | No | Bundle name.|
| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. |
| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).|
| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. |
| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). |
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit **Want** and is used to filter ability types. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). |
| moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.|
**Example**
- Basic usage
- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility).
```ts
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry" // moduleName is optional.
};
this.context.startAbility(want, (error) => {
......@@ -46,13 +46,13 @@ import Want from '@ohos.application.Want';
})
```
- Data is transferred through user-defined fields. The following data types are supported:
- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility):
* String
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
parameters: {
keyForString: "str",
},
......@@ -61,8 +61,8 @@ import Want from '@ohos.application.Want';
* Number
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
parameters: {
keyForInt: 100,
keyForDouble: 99.99,
......@@ -72,8 +72,8 @@ import Want from '@ohos.application.Want';
* Boolean
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
parameters: {
keyForBool: true,
},
......@@ -82,8 +82,8 @@ import Want from '@ohos.application.Want';
* Object
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
parameters: {
keyForObject: {
keyForObjectString: "str",
......@@ -97,8 +97,8 @@ import Want from '@ohos.application.Want';
* Array
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
parameters: {
keyForArrayString: ["str1", "str2", "str3"],
keyForArrayInt: [100, 200, 300, 400],
......@@ -110,16 +110,16 @@ import Want from '@ohos.application.Want';
* File descriptor (FD)
```ts
import fileio from '@ohos.fileio';
var fd;
let fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry", // moduleName is optional.
"parameters": {
"keyFd":{"type":"FD", "value":fd}
......@@ -131,4 +131,6 @@ import Want from '@ohos.application.Want';
})
```
- For more details and examples, see [Want](../../application-models/want-overview.md).
<!--no_check-->
# Window Extension Ability
# @ohos.application.WindowExtensionAbility (WindowExtensionAbility)
**WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows.
> **NOTE**
......
# Configuration
The **Configuration** module provides environment configuration information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import Configuration from '@ohos.application.Configuration';
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| language | string | Yes| Yes| Language of the application.|
| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.|
| direction<sup>9+</sup> | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.|
| screenDensity<sup>9+</sup> | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).|
| displayId<sup>9+</sup> | number | Yes| No| ID of the display where the application is located.|
| hasPointerDevice<sup>9+</sup> | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.|
# ContinuationResult
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## ContinuationResult
......
# @ohos.bundle.distributedBundle
The **distributedBundle** module provides APIs for managing distributed bundles.
> **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 are system APIs.
## Modules to Import
```
import distributedBundle from '@ohos.bundle.distributedBundle';
```
## System Capability
SystemCapability.BundleManager.DistributedBundleFramework
## Required Permissions
| Permission | Permission Level | Description |
| ------------------------------------------ | ------------ | ------------------ |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all bundles.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback\<RemoteAbilityInfo>): void;
Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. |
| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|--------------------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
}, (err, data) => {
if (err) {
console.error('Operation failed:' + JSON.stringify(err));
} else {
console.info('Operation succeed:' + JSON.stringify(data));
}
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName): Promise\<RemoteAbilityInfo>;
Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | -------------------------------------------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
}).then(data => {
console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => {
console.error('Operation failed:' + JSON.stringify(err));
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementNames: Array\<ElementName>, callback: AsyncCallback\<Array\<RemoteAbilityInfo>>): void;
Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. |
| callback | AsyncCallback\<Array\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
[
{
deviceId: '1',
bundleName: 'com.example.application1',
abilityName: 'MainAbility1'
},
{
deviceId: '1',
bundleName: 'com.example.application2',
abilityName: 'MainAbility'
}
], (err, data) => {
if (err) {
console.error('Operation failed:' + JSON.stringify(err));
} else {
console.info('Operation succeed:' + JSON.stringify(data));
}
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementNames: Array\<ElementName>): Promise\<Array\<RemoteAbilityInfo>>;
Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | --------------------------------------------------- | ---- | ----------------------- |
| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<Array<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)>> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
[
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
},
{
deviceId: '1',
bundleName: 'com.example.application2',
abilityName: 'MainAbility'
}
]).then(data => {
console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => {
console.error('Operation failed:' + JSON.stringify(err));
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName, locale: string, callback: AsyncCallback\<RemoteAbilityInfo>): void;
Obtains information about the remote ability that matches the given element name and locale. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. |
| locale | string |Yes| Target locale.|
| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
}, 'zh-Hans-CN', (err, data) => {
if (err) {
console.error('Operation failed:' + JSON.stringify(err));
} else {
console.info('Operation succeed:' + JSON.stringify(data));
}
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName, locale: string): Promise\<RemoteAbilityInfo>;
Obtains information about the remote ability that matches the given element name and locale. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | -------------------------------------------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.|
| locale | string |Yes| Target locale.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
}, 'zh-Hans-CN').then(data => {
console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => {
console.error('Operation failed:' + JSON.stringify(err));
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementNames: Array\<ElementName>, locale: string, callback: AsyncCallback\<Array\<RemoteAbilityInfo>>): void;
Obtains information about remote abilities that match the given element names and locales. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- |
| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. |
| locale | string |Yes| Target locale.|
| callback | AsyncCallback\<Array\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID | Error Message |
|---------------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
[
{
deviceId: '1',
bundleName: 'com.example.application1',
abilityName: 'MainAbility1'
},
{
deviceId: '1',
bundleName: 'com.example.application2',
abilityName: 'MainAbility'
}
], 'zh-Hans-CN', (err, data) => {
if (err) {
console.error('Operation failed:' + JSON.stringify(err));
} else {
console.info('Operation succeed:' + JSON.stringify(data));
}
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementNames: Array\<ElementName>, locale: string): Promise\<Array\<RemoteAbilityInfo>>;
Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.DistributedBundleFramework
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | --------------------------------------------------- | ---- | ----------------------- |
| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.|
| locale | string |Yes| Target locale.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<Array<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)>> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
|----------|-------------------------|
| 17700001 | The specified bundle name is not found. |
| 17700003 | The specified ability name is not found. |
| 17700007 | The specified device ID is not found. |
| 17700027 | The distributed service is not running. |
**Example**
```ts
try {
distributedBundle.getRemoteAbilityInfo(
[
{
deviceId: '1',
bundleName: 'com.example.application',
abilityName: 'MainAbility'
},
{
deviceId: '1',
bundleName: 'com.example.application2',
abilityName: 'MainAbility'
}
], 'zh-Hans-CN').then(data => {
console.info('Operation succeed:' + JSON.stringify(data));
}).catch(err => {
console.error('Operation failed:' + JSON.stringify(err));
});
} catch (err) {
console.error('Operation failed:' + JSON.stringify(err));
}
```
# AbilityResult
The **AbilityResult** module defines the result code and data returned when an ability is started or destroyed.
The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult).
> **NOTE**
>
......@@ -10,17 +10,5 @@ The **AbilityResult** module defines the result code and data returned when an a
| Name | Readable | Writable | Type | Mandatory| Description |
| ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ |
| resultCode | Yes | No | number | No | Result code returned when the ability is started or destroyed. |
| want | Yes | No | [Want](./js-apis-app-ability-want.md) | No | Data returned when the ability is destroyed.|
**Example**
```ts
let want = {
bundleName: 'com.example.mydocapplication',
abilityName: 'MainAbility',
};
this.context.startAbilityForResult(want, (error, data) => {
let resultCode = data.resultCode;
let want = data.want;
});
```
| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. |
| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated. |
# ConnectOptions
The **ConnectOptions** module defines the options for connection.
**ConnectOptions** can be used as an input parameter to receive status changes during the connection to a background service. For example, it is used as an input parameter of [connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) to connect to a ServiceExtensionAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Mandatory | Description |
| ------------ | -------- | ---- | ------------------------- |
| onConnect<sup>7+</sup> | function | Yes | Callback invoked when the connection is successful. |
| onDisconnect<sup>7+</sup> | function | Yes | Callback invoked when the connection fails. |
| onFailed<sup>7+</sup> | function | Yes | Callback invoked when **connectAbility** fails to be called.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | ID of the Service ability connected.|
**Example**
```ts
import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}
function onFailedCallback(code){
console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code)
}
var connectId = featureAbility.connectAbility(
{
deviceId: "",
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
| onConnect<sup>7+</sup> | function | Yes | Callback invoked when a connection is set up. |
| onDisconnect<sup>7+</sup> | function | Yes | Callback invoked when a connection is interrupted. |
| onFailed<sup>7+</sup> | function | Yes | Callback invoked when a connection fails.|
# DataAbilityHelper
The **DataAbilityHelper** object is obtained through [acquireDataAbilityHelper](js-apis-ability-featureAbility.md#featureabilityacquiredataabilityhelper7).
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -9,15 +11,15 @@
Import the following modules based on the actual situation before using the current module:
```ts
import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb'
import ohos_data_ability from '@ohos.data.dataAbility';
import ohos_data_rdb from '@ohos.data.rdb';
```
## DataAbilityHelper.openFile
openFile(uri: string, mode: string, callback: AsyncCallback\<number>): void
Opens a file with a specified URI. This API uses an asynchronous callback to return the result.
Opens a file with a specified URI. This API uses an asynchronous callback to return a file descriptor.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -26,22 +28,19 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | Mode for opening the file. The value can be **rwt**. |
| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the file descriptor.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var mode = "rwt";
DAHelper.openFile(
"dataability:///com.example.DataAbility",
mode,
(err) => {
console.info("==========================>Called=======================>");
var mode = "rw";
DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => {
console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -49,7 +48,7 @@ DAHelper.openFile(
openFile(uri: string, mode: string): Promise\<number>
Opens a file with a specified URI. This API uses a promise to return the result.
Opens a file with a specified URI. This API uses a promise to return a file descriptor.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -58,7 +57,7 @@ Opens a file with a specified URI. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ------------------------ |
| uri | string | Yes | URI of the file to open.|
| mode | string | Yes | Mode for opening the file. The value can be **rwt**. |
| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. |
**Return value**
......@@ -69,15 +68,13 @@ Opens a file with a specified URI. This API uses a promise to return the result.
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var mode = "rwt";
DAHelper.openFile(
"dataability:///com.example.DataAbility",
mode).then((data) => {
console.info("==========================>openFileCallback=======================>");
var mode = "rw";
DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => {
console.info("openFile data: " + JSON.stringify(data));
});
```
......@@ -85,7 +82,7 @@ DAHelper.openFile(
on(type: 'dataChange', uri: string, callback: AsyncCallback\<void>): void
Registers an observer to observe data specified by a given URI. This API uses an asynchronous callback to return the result.
Registers an observer to listen for changes in the data specified by a given URI.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -93,32 +90,32 @@ Registers an observer to observe data specified by a given URI. This API uses an
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Type of the event to observe. The value is **dataChange**. |
| type | string | Yes | The value **dataChange** means data changes. |
| uri | string | Yes | URI of the data.|
| callback | AsyncCallback\<void> | Yes | Callback invoked when the data is changed. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
var helper = featureAbility.acquireDataAbilityHelper(
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
function onChangeNotify() {
console.info("==========================>onChangeNotify=======================>");
console.info("onChangeNotify call back");
};
helper.on(
DAHelper.on(
"dataChange",
"dataability:///com.example.DataAbility",
onChangeNotify
)
);
```
## DataAbilityHelper.off
off(type: 'dataChange', uri: string, callback?: AsyncCallback\<void>): void
Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result.
Deregisters the observer that listens for changes in the data specified by a given URI.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -126,36 +123,36 @@ Deregisters the observer used to observe data specified by a given URI. This API
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Type of the event to observe. The value is **dataChange**. |
| type | string | Yes | The value **dataChange** means data changes. |
| uri | string | Yes | URI of the data.|
| callback | AsyncCallback\<void> | No | Callback used to return the result. |
| callback | AsyncCallback\<void> | No | Callback of the listener to deregister. If the callback is set to **null**, all data change listeners are canceled. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
var helper = featureAbility.acquireDataAbilityHelper(
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
function onChangeNotify() {
console.info("==========================>onChangeNotify=======================>");
console.info("onChangeNotify call back");
};
helper.off(
DAHelper.off(
"dataChange",
"dataability:///com.example.DataAbility",
)
helper.off(
onChangeNotify
);
DAHelper.off(
"dataChange",
"dataability:///com.example.DataAbility",
onChangeNotify
)
);
```
## DataAbilityHelper.getType
getType(uri: string, callback: AsyncCallback\<string>): void
Obtains the MIME type of the data specified by a given URI. This API uses an asynchronous callback to return the result.
Obtains the media resource type of the data specified by a given URI. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -164,19 +161,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses an asy
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | --------------------------------------------- |
| uri | string | Yes | URI of the data. |
| callback | AsyncCallback\<string> | Yes | Callback used to return the MIME type.|
| callback | AsyncCallback\<string> | Yes | Callback used to return the media resource type.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.getType(
"dataability:///com.example.DataAbility",
(err, data) => {
console.info("==========================>Called=======================>");
DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => {
console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -184,7 +179,7 @@ DAHelper.getType(
getType(uri: string): Promise\<string>
Obtains the MIME type of the data specified by a given URI. This API uses a promise to return the result.
Obtains the media resource type of the data specified by a given URI. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -198,19 +193,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses a prom
| Type | Description |
| ---------------- | ----------------------------------- |
| Promise\<string> | Promise used to return the MIME type.|
| Promise\<string> | Promise used to return the media resource type.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.getType(
"dataability:///com.example.DataAbility"
).then((data) => {
console.info("==========================>getTypeCallback=======================>");
DAHelper.getType("dataability:///com.example.DataAbility").then((data) => {
console.info("getType data: " + JSON.stringify(data));
});
```
......@@ -218,7 +211,7 @@ DAHelper.getType(
getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>): void
Obtains the supported MIME types of a specified file. This API uses an asynchronous callback to return the result.
Obtains the supported media resource types of a specified file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -227,31 +220,26 @@ Obtains the supported MIME types of a specified file. This API uses an asynchron
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------ | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME type of the file. |
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the supported MIME types.|
| mimeTypeFilter | string | Yes | Media resource type of the file to obtain. |
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array holding the media resource type.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.getFileTypes(
"dataability:///com.example.DataAbility",
"image/*",
(err, data) => {
console.info("==========================>Called=======================>");
DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => {
console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
## DataAbilityHelper.getFileTypes
getFileTypes(uri: string, mimeTypeFilter: string): Promise\<Array\<string>>
Obtains the supported MIME types of a specified file. This API uses a promise to return the result.
Obtains the supported media resource types of a specified file. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -260,26 +248,23 @@ Obtains the supported MIME types of a specified file. This API uses a promise to
| Name | Type | Mandatory| Description |
| -------------- | ------ | ---- | ---------------------------- |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME type of the file.|
| mimeTypeFilter | string | Yes | Media resource type of the file to obtain.|
**Return value**
| Type | Description |
| ------------------------ | ------------------------ |
| Promise\<Array\<string>> | Promise used to return the supported MIME types.|
| Promise\<Array\<string>> | Promise used to return an array holding the media resource type.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.getFileTypes(
"dataability:///com.example.DataAbility",
"image/*"
).then((data) => {
console.info("==========================>getFileTypesCallback=======================>");
DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => {
console.info("getFileTypes data: " + JSON.stringify(data));
});
```
......@@ -301,14 +286,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.normalizeUri(
"dataability:///com.example.DataAbility",
(err, data) => {
console.info("==========================>Called=======================>");
DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => {
console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -335,14 +318,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.normalizeUri(
"dataability:///com.example.DataAbility",
).then((data) => {
console.info("==========================>normalizeUriCallback=======================>");
DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => {
console.info("normalizeUri data: " + JSON.stringify(data));
});
```
......@@ -358,25 +339,21 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | --------------------------------------------------- |
| uri | string | Yes | URI object to normalize. |
| uri | string | Yes | URI object to denormalize. |
| callback | AsyncCallback\<string> | Yes | Callback used to return the denormalized URI object.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.denormalizeUri(
"dataability:///com.example.DataAbility",
(err, data) => {
console.info("==========================>Called=======================>");
DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => {
console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
## DataAbilityHelper.denormalizeUri
denormalizeUri(uri: string): Promise\<string>
......@@ -400,14 +377,12 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.denormalizeUri(
"dataability:///com.example.DataAbility",
).then((data) => {
console.info("==========================>denormalizeUriCallback=======================>");
DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => {
console.info("denormalizeUri data: " + JSON.stringify(data));
});
```
......@@ -423,19 +398,17 @@ Notifies the registered observer of a change to the data specified by the URI. T
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ |
| uri | string | Yes | URI of the data.|
| uri | string | Yes | URI of the data that changes.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
var helper = featureAbility.acquireDataAbilityHelper(
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
helper.notifyChange(
"dataability:///com.example.DataAbility",
(err) => {
DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => {
console.info("==========================>Called=======================>");
});
```
......@@ -452,7 +425,7 @@ Notifies the registered observer of a change to the data specified by the URI. T
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ------------------------ |
| uri | string | Yes | URI of the data.|
| uri | string | Yes | URI of the data that changes.|
**Return value**
......@@ -463,14 +436,12 @@ Notifies the registered observer of a change to the data specified by the URI. T
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
DAHelper.notifyChange(
"dataability:///com.example.DataAbility",
).then(() => {
console.info("==========================>notifyChangeCallback=======================>");
DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => {
console.info("================>notifyChangeCallback================>");
});
```
......@@ -493,7 +464,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
......@@ -502,12 +473,9 @@ const valueBucket = {
"age": 22,
"salary": 200.5,
"blobType": "u8",
}
DAHelper.insert(
"dataability:///com.example.DataAbility",
valueBucket,
(err, data) => {
console.info("==========================>Called=======================>");
};
DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => {
console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -535,7 +503,7 @@ Inserts a single data record into the database. This API uses a promise to retur
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
......@@ -544,12 +512,9 @@ const valueBucket = {
"age": 221,
"salary": 20.5,
"blobType": "u8",
}
DAHelper.insert(
"dataability:///com.example.DataAbility",
valueBucket
).then((data) => {
console.info("==========================>insertCallback=======================>");
};
DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => {
console.info("insert data: " + JSON.stringify(data));
});
```
......@@ -572,18 +537,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",},
{"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",},
{"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",})
DAHelper.batchInsert(
"dataability:///com.example.DataAbility",
cars,
(err, data) => {
console.info("==========================>Called=======================>");
{"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",});
DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => {
console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -600,7 +562,7 @@ Inserts multiple data records into the database. This API uses a promise to retu
| Name | Type | Mandatory| Description |
| ------------ | ----------------------- | ---- | ------------------------ |
| uri | string | Yes | URI of the data to insert.|
| valuesBucket | Array<rdb.ValuesBucket> | Yes | Data record to insert. |
| valuesBucket | Array<rdb.ValuesBucket> | Yes | Data records to insert. |
**Return value**
......@@ -611,18 +573,15 @@ Inserts multiple data records into the database. This API uses a promise to retu
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",},
{"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",},
{"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",})
DAHelper.batchInsert(
"dataability:///com.example.DataAbility",
cars
).then((data) => {
console.info("==========================>batchInsertCallback=======================>");
{"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",});
DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => {
console.info("batchInsert data: " + JSON.stringify(data));
});
```
......@@ -645,17 +604,14 @@ Deletes one or more data records from the database. This API uses an asynchronou
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.delete(
"dataability:///com.example.DataAbility",
da,
(err, data) => {
console.info("==========================>Called=======================>");
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => {
console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -683,17 +639,14 @@ Deletes one or more data records from the database. This API uses a promise to r
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.delete(
"dataability:///com.example.DataAbility",
da
).then((data) => {
console.info("==========================>deleteCallback=======================>");
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => {
console.info("delete data: " + JSON.stringify(data));
});
```
......@@ -717,8 +670,8 @@ Updates data records in the database. This API uses an asynchronous callback to
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
......@@ -727,14 +680,10 @@ const va = {
"age": 21,
"salary": 20.5,
"blobType": "u8",
}
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.update(
"dataability:///com.example.DataAbility",
va,
da,
(err, data) => {
console.info("==========================>Called=======================>");
};
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => {
console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -763,8 +712,8 @@ Updates data records in the database. This API uses a promise to return the resu
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
......@@ -773,14 +722,10 @@ const va = {
"age": 21,
"salary": 20.5,
"blobType": "u8",
}
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.update(
"dataability:///com.example.DataAbility",
va,
da
).then((data) => {
console.info("==========================>updateCallback=======================>");
};
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => {
console.info("update data: " + JSON.stringify(data));
});
```
......@@ -804,19 +749,15 @@ Queries data in the database. This API uses an asynchronous callback to return t
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var cars=new Array("value1", "value2", "value3", "value4");
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.query(
"dataability:///com.example.DataAbility",
cars,
da,
(err, data) => {
console.info("==========================>Called=======================>");
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => {
console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
```
......@@ -847,27 +788,23 @@ Queries data in the database. This API uses a promise to return the result.
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility"
);
var cars=new Array("value1", "value2", "value3", "value4");
let da = new ohos_data_ability.DataAbilityPredicates()
DAHelper.query(
"dataability:///com.example.DataAbility",
cars,
da
).then((data) => {
console.info("==========================>queryCallback=======================>");
var cars = new Array("value1", "value2", "value3", "value4");
let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => {
console.info("query data: " + JSON.stringify(data));
});
```
## DataAbilityHelper.call
call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap>
call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void
Calls the extended API of the Data ability. This API uses a promise to return the result.
Calls an extended API of the DataAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -875,35 +812,35 @@ Calls the extended API of the Data ability. This API uses a promise to return th
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------- | ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". |
| method | string | Yes | Name of the API to call. |
| arg | string | Yes |Parameter to pass. |
| arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. |
**Return value**
| Type| Description|
|------ | ------- |
|Promise\<[PacMap](#pacmap)> | Promise used to return the result.|
| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility");
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}).then((data) => {
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility"
);
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility",
"method", "arg", {"key1":"value1"}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + err);
return;
}
console.info('Operation succeeded: ' + data);
}).catch((error) => {
console.error('Operation failed. Cause: ' + error);
});
```
## DataAbilityHelper.call
call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void
call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap>
Calls the extended API of the Data ability. This API uses an asynchronous callback to return the result.
Calls an extended API of the DataAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -911,24 +848,30 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------- | ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". |
| method | string | Yes | Name of the API to call. |
| arg | string | Yes |Parameter to pass. |
| arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. |
| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. |
**Return value**
| Type| Description|
|------ | ------- |
|Promise\<[PacMap](#pacmap)> | Promise used to return the result.|
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility");
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + err);
return;
}
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility"
);
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility",
"method", "arg", {"key1":"value1"}).then((data) => {
console.info('Operation succeeded: ' + data);
}).catch((error) => {
console.error('Operation failed. Cause: ' + error);
});
```
......@@ -936,17 +879,17 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "
executeBatch(uri: string, operations: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void;
Operates data in the database. This API uses an asynchronous callback to return the result.
Operates data in the database in batches. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------- | ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".|
| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. |
| callback | AsyncCallback\<Array\<[DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md)>> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. |
| ----------| ---------------------------------| ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".|
| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. |
| callback | AsyncCallback\<Array\<[DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md)>> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. |
**Example**
......@@ -955,7 +898,9 @@ import featureAbility from '@ohos.ability.featureAbility';
// Select the operations to be performed on the database according to the DataAbilityOperation array.
let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility");
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility"
);
dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + err);
......@@ -969,7 +914,7 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi
executeBatch(uri: string, operations: Array\<DataAbilityOperation>): Promise\<Array\<DataAbilityResult>>;
Operates data in the database. This API uses a promise to return the result.
Operates data in the database in batches. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
......@@ -977,14 +922,14 @@ Operates data in the database. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ---------- | -------------------------------| ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".|
| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".|
| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. |
**Return value**
| Type| Description|
|------ | ------- |
|Promise\<Array\<[DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md)>> | Callback used to return the result of each operation in the **DataAbilityResult** array.|
|Promise\<Array\<[DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md)>> | Promise used to return the result of each operation in the **DataAbilityResult** array.|
**Example**
......@@ -993,8 +938,10 @@ import featureAbility from '@ohos.ability.featureAbility';
// Select the operations to be performed on the database according to the DataAbilityOperation array.
let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility");
dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => {
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility"
);
dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => {
console.info('Operation succeeded: ' + data);
}).catch((error) => {
console.error('Operation failed. Cause: ' + error);
......
# DataAbilityOperation
The **DataAbilityOperation** module defines the operation on Data abilities.
The **DataAbilityOperation** module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information.
> **NOTE**
>
......@@ -11,7 +11,7 @@ The **DataAbilityOperation** module defines the operation on Data abilities.
| Name | Template | Mandatory| Description |
| -------- | -------- | --------| -------- |
| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". |
| type | featureAbility.DataAbilityOperationType | Yes | Operation type. |
| valuesBucket? | rdb.ValuesBucket | No | Data value to set. |
| valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. |
......@@ -19,48 +19,3 @@ The **DataAbilityOperation** module defines the operation on Data abilities.
| predicatesBackReferences? | Map\<number, number> | No | Back references of the predicates. |
| interrupted? | boolean | No | Whether batch operations can be interrupted. |
| expectedCount? | number | No | Expected number of rows to be updated or deleted. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility");
let DAHelper;
try {
DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri);
if(DAHelper == null){
console.error('DAHelper is null');
return;
}
} catch (err) {
console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err));
return;
}
let valueBucket = {
"name": "DataAbilityHelperTest",
"age": 24,
"salary": 2024.20,
};
let dataAbilityOperation = {
uri: dataAbilityUri,
type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
valuesBucket: valueBucket,
predicates: null,
expectedCount: 1,
PredicatesBackReferences: {},
interrupted: true
}
let operations = [
dataAbilityOperation
];
try {
DAHelper.executeBatch(dataAbilityUri, operations,
(err, data) => {
console.log("executeBatch, data: " + JSON.stringify(data));
}
);
} catch (err) {
console.error('executeBatch fail: ' + JSON.stringify(err));
}
```
# DataAbilityResult
The **DataAbilityResult** module defines the operation result on Data abilities.
The **DataAbilityResult** module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object.
> **NOTE**
>
......@@ -11,33 +11,36 @@ The **DataAbilityResult** module defines the operation result on Data abilities.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| uri? | string | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". |
| uri? | string | No | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". |
| count? | number | No | Number of rows affected by the operation. |
**Example**
```ts
import featureAbility from '@ohos.ability.featureAbility'
let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility");
let DAHelper;
try {
// Perform database operations in batches.
function executeBatchOperation() {
let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility");
let DAHelper;
try {
DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri);
if(DAHelper == null){
if (DAHelper == null) {
console.error('DAHelper is null');
return;
}
} catch (err) {
} catch (err) {
console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err));
return;
}
}
let valueBucket = {
let valueBucket = {
"name": "DataAbilityHelperTest",
"age": 24,
"salary": 2024.20,
};
let operations = [
{
};
let operations = [
{
uri: dataAbilityUri,
type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
valuesBucket: valueBucket,
......@@ -45,8 +48,8 @@ let operations = [
expectedCount: 1,
PredicatesBackReferences: {},
interrupted: true,
},
{
},
{
uri: dataAbilityUri,
type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
valuesBucket: valueBucket,
......@@ -54,11 +57,11 @@ let operations = [
expectedCount: 1,
PredicatesBackReferences: {},
interrupted: true,
}
];
}
];
try {
let promise = DAHelper.executeBatch(dataAbilityUri, operations).then((data) => {
try {
DAHelper.executeBatch(dataAbilityUri, operations).then((data) => {
for (let i = 0; i < data.length; i++) {
let dataAbilityResult = data[i];
console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri);
......@@ -67,7 +70,8 @@ try {
}).catch(err => {
console.error('executeBatch error: ' + JSON.stringify(err));
});
} catch (err) {
} catch (err) {
console.error('executeBatch error: ' + JSON.stringify(err));
}
}
```
# StartAbilityParameter
The **StartAbilityParameter** module defines the parameters for starting an ability.
The **StartAbilityParameter** module defines the parameters for starting an ability. The parameters can be used as input parameters in [startAbility](js-apis-ability-featureAbility.md#featureabilitystartability) to start the specified ability.
> **NOTE**
>
......@@ -11,8 +11,8 @@ The **StartAbilityParameter** module defines the parameters for starting an abil
| Name | Type | Mandatory | Description |
| ------------------- | -------- | ---- | -------------------------------------- |
| want | [Want](js-apis-application-want.md)| Yes | Information about the ability to start. |
| abilityStartSetting | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.|
| want | [Want](js-apis-application-want.md)| Yes | Want information about the target ability. |
| abilityStartSetting | {[key: string]: any} | No | Special attribute of the target ability. This attribute can be passed in the call.|
**Example**
```ts
......@@ -20,7 +20,7 @@ import featureAbility from '@ohos.ability.featureAbility'
let Want = {
bundleName: "com.example.abilityStartSettingApp2",
abilityName: "com.example.abilityStartSettingApp.MainAbility",
abilityName: "com.example.abilityStartSettingApp.EntryAbility",
}
let abilityStartSetting ={
......@@ -31,13 +31,15 @@ let abilityStartSetting ={
}
let startAbilityParameter = {
want:Want,
abilityStartSetting:abilityStartSetting
want : Want,
abilityStartSetting : abilityStartSetting
}
featureAbility.startAbility(startAbilityParameter, (err,data)=>{
try {
featureAbility.startAbility(startAbilityParameter, (err, data) => {
console.log('errCode : ' + JSON.stringify(err));
console.log('data : ' + JSON.stringify(data));
});
} catch(error) {
console.log("startAbility error: " + JSON.stringify(error));
}
......
# Want
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
> **NOTE**
>
......@@ -10,26 +10,26 @@ Want is a carrier for information transfer between objects (application componen
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name of the application. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. |
| bundleName | string | No | Bundle name.|
| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. |
| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).|
| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. |
| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). |
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. |
| entities | Array\<string> | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). |
| moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.|
**Example**
- Basic usage
- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility).
```ts
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry" // moduleName is optional.
};
this.context.startAbility(want, (error) => {
......@@ -38,20 +38,22 @@ Want is a carrier for information transfer between objects (application componen
})
```
- Passing a file descriptor (FD)
- Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility):
```ts
import fileio from '@ohos.fileio';
var fd;
// ...
let fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
var want = {
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "EntryAbility",
"moduleName": "entry", // moduleName is optional.
"parameters": {
"keyFd":{"type":"FD", "value":fd}
......@@ -61,5 +63,9 @@ Want is a carrier for information transfer between objects (application componen
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
// ...
```
- For more details and examples, see [Want](../../application-models/want-overview.md).
<!--no_check-->
# AppVersionInfo
The **AppVersionInfo** module defines the application version information.
The **AppVersionInfo** module defines the application version information. You can use [getAppVersionInfo](js-apis-inner-app-context.md#contextgetappversioninfo7) to obtain the version information of the current application.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
| Name | Type | Readable | Writable | Description |
| ----------- | ------ | ---- | ---- | ------- |
| appName | string | Yes | No | Module name. |
| versionCode | number | Yes | No | Module description.|
| versionName | string | Yes | No | Module description ID.|
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
```ts
let appName;
let versionCode;
let versionName;
this.context.getAppVersionInfo((error, data) => {
console.info('getAppVersionInfo data is:' + JSON.stringify(data));
appName = data.appName;
versionCode = data.versionCode;
versionName = data.versionName;
});
```
| Name | Type | Readable| Writable| Description |
| ----------- | ------ | ---- | ---- | -------------- |
| appName | string | Yes | No | Application name. |
| versionCode | number | Yes | No | Application version code.|
| versionName | string | Yes | No | Application version name. |
......@@ -5,11 +5,12 @@ The **Context** module provides context for abilities or applications. It allows
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module can be used only in the FA model.
## Usage
The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows:
The **Context** object is created in a **featureAbility** and returned through its [getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext) API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows:
```ts
import featureAbility from '@ohos.ability.featureAbility';
......@@ -93,14 +94,15 @@ Verifies whether a specific PID and UID have the given permission. This API uses
```ts
import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle';
import bundle from '@ohos.bundle.bundleManager';
var context = featureAbility.getContext();
bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{
context.verifyPermission("com.example.permission", {uid:datainfo.uid}, (err, data) =>{
context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{
console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
});
});
```
For details about **getBundleInfo** in the sample code, see [bundleManager](js-apis-bundleManager.md).
......@@ -250,7 +252,7 @@ Obtains information about the current application. This API uses an asynchronous
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------ |
| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information.|
| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | Callback used to return the application information.|
**Example**
......@@ -352,7 +354,7 @@ Obtains the display orientation of this ability. This API uses an asynchronous c
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.|
| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Yes | Callback used to return the display orientation.|
**Example**
......@@ -376,7 +378,7 @@ Obtains the display orientation of this ability. This API uses a promise to retu
| Type | Description |
| ---------------------------------------- | --------- |
| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.|
| Promise\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Promise used to return the display orientation.|
**Example**
......@@ -448,7 +450,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ------------ |
| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.|
| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | Display orientation to set.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the display orientation. |
**Example**
......@@ -457,7 +459,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal
import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle';
var context = featureAbility.getContext();
var orientation=bundle.DisplayOrientation.UNSPECIFIED
var orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation, (err) => {
console.info("setDisplayOrientation err: " + JSON.stringify(err));
});
......@@ -475,7 +477,7 @@ Sets the display orientation for this ability. This API uses a promise to return
| Type | Description |
| ---------------------------------------- | ---------------------------------------- |
| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) |
| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) |
| Promise\<void> | Promise used to return the display orientation. |
**Example**
......@@ -484,7 +486,7 @@ Sets the display orientation for this ability. This API uses a promise to return
import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle';
var context = featureAbility.getContext();
var orientation=bundle.DisplayOrientation.UNSPECIFIED
var orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation).then((data) => {
console.info("setDisplayOrientation data: " + JSON.stringify(data));
});
......@@ -510,7 +512,7 @@ Sets whether to show this feature at the top of the lock screen so that the feat
```ts
import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext();
var show=true
var show = true;
context.setShowOnLockScreen(show, (err) => {
console.info("setShowOnLockScreen err: " + JSON.stringify(err));
});
......@@ -541,7 +543,7 @@ Sets whether to show this feature at the top of the lock screen so that the feat
```ts
import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext();
var show=true
var show = true;
context.setShowOnLockScreen(show).then((data) => {
console.info("setShowOnLockScreen data: " + JSON.stringify(data));
});
......@@ -567,7 +569,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses
```ts
import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext();
var wakeUp=true
var wakeUp = true;
context.setWakeUpScreen(wakeUp, (err) => {
console.info("setWakeUpScreen err: " + JSON.stringify(err));
});
......@@ -598,7 +600,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses
```ts
import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext();
var wakeUp=true
var wakeUp = true;
context.setWakeUpScreen(wakeUp).then((data) => {
console.info("setWakeUpScreen data: " + JSON.stringify(data));
});
......@@ -673,7 +675,7 @@ This API is available only to Page abilities.
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<[ElementName](js-apis-bundle-ElementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.|
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.|
**Example**
......@@ -701,7 +703,7 @@ This API is available only to Page abilities.
| Type | Description |
| --------------------- | ------------------------------------ |
| Promise\<[ElementName](js-apis-bundle-ElementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.|
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.|
**Example**
......@@ -769,7 +771,7 @@ context.getProcessName().then((data) => {
getCallingBundle(callback: AsyncCallback\<string>): void
Obtains the bundle name of the calling ability. This API uses an asynchronous callback to return the result.
Obtains the bundle name of the caller ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -795,7 +797,7 @@ context.getCallingBundle((err, data) => {
getCallingBundle(): Promise\<string>
Obtains the bundle name of the calling ability. This API uses a promise to return the result.
Obtains the bundle name of the caller ability. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -925,7 +927,7 @@ If the distributed file path does not exist, the system will create one and retu
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback\<string> | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.|
| callback | AsyncCallback\<string> | Yes | Callback used to return the distributed file path.<br>If the path does not exist, the system will create one and return the created path.|
**Example**
......@@ -951,7 +953,7 @@ If the distributed file path does not exist, the system will create one and retu
| Type | Description |
| ---------------- | ----------------------------------- |
| Promise\<string> | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.|
| Promise\<string> | Promise used to return the distributed file path. If this API is called for the first time, a path will be created.|
**Example**
......@@ -1023,7 +1025,7 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------------- |
| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.|
| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.|
**Example**
......@@ -1047,7 +1049,7 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to
| Type | Description |
| ---------------------------------------- | ------------------ |
| Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.|
| Promise\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.|
**Example**
......@@ -1119,7 +1121,7 @@ Obtains information about this ability. This API uses an asynchronous callback t
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------------- |
| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.|
| callback | AsyncCallback\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | Callback used to return the ability information.|
**Example**
......@@ -1143,7 +1145,7 @@ Obtains information about this ability. This API uses a promise to return the re
| Type | Description |
| ---------------------------------------- | ------------------ |
| Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.|
| Promise\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Promise used to return the ability information.|
**Example**
......
# ProcessInfo
The **ProcessInfo** module defines process information.
The **ProcessInfo** module defines process information. You can use [getProcessInfo](js-apis-inner-app-context.md#contextgetprocessinfo7) to obtain information about the processes running on the current ability.
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module can be used only in the FA model.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
......@@ -8,14 +8,11 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in
## Usage
The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**.
An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**.
```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
```
## AbilityDelegator
......
# AbilityDelegatorArgs
The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup.
The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegatorArgs** object during the execution of test cases.
> **NOTE**
>
......@@ -8,7 +8,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi
## Usage
The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**.
An **AbilityDelegatorArgs** object is obtained by calling [getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments) in **AbilityDelegatorRegistry**.
## AbilityDelegatorArgs
......
......@@ -8,7 +8,7 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie
## Usage
The ability monitor can be set by calling **addAbilityMonitor** in **abilityDelegator**.
**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability.
## AbilityMonitor
......@@ -31,7 +31,6 @@ Describes an ability monitor.
```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
......@@ -42,7 +41,7 @@ var monitor = {
onAbilityCreate: onAbilityCreateCallback
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
console.info("addAbilityMonitor callback");
});
......
......@@ -8,7 +8,7 @@ The **AbilityRunningInfo** module defines the running information and state of a
## Usage
The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**.
The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**.
## Attributes
......
......@@ -29,4 +29,4 @@ class MyAbilityStage extends AbilityStage {
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.|
| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.|
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration for the environment where the application is running.|
# AbilityStateData
The **AbilityStateData** module defines the ability state information.
The **AbilityStateData** module defines the ability state information, which can be obtained through the **onAbilityStateChanged** lifecycle callback of [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md). The callback can be invoked after a lifecycle change listener is registered through [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- |
| pid<sup>8+</sup> | number | Yes | No | Process ID. |
| bundleName<sup>8+</sup> | string | Yes | No | Bundle name of an application. |
| bundleName<sup>8+</sup> | string | Yes | No | Bundle name. |
| abilityName<sup>8+</sup> | string | Yes | No | Ability name. |
| uid<sup>8+</sup> | number | Yes | No | User ID. |
| state<sup>8+</sup> | number | Yes | No | Ability state. |
| state<sup>8+</sup> | number | Yes | No | [Ability state](#ability-states). |
| moduleName<sup>9+</sup> | string | Yes | No | Name of the HAP file to which the ability belongs. |
| abilityType<sup>8+</sup> | string | Yes | No | Ability type. |
| abilityType<sup>8+</sup> | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.|
**Example**
```ts
import appManager from "@ohos.application.appManager"
#### Ability States
appManager.getForegroundApplications((error, data) => {
for(let i=0; i<data.length; i++) {
let appStateData = data[i];
console.info('appStateData.pid: ' + appStateData.pid);
console.info('appStateData.bundleName: ' + appStateData.bundleName);
console.info('appStateData.abilityName: ' + appStateData.abilityName);
console.info('appStateData.uid: ' + appStateData.uid);
console.info('appStateData.state: ' + appStateData.state);
console.info('appStateData.moduleName: ' + appStateData.moduleName);
console.info('appStateData.abilityType: ' + appStateData.abilityType);
}
});
```
| Value | State | Description |
| ---- | -------------------------- | ---------------------- |
| 0 | ABILITY_STATE_CREATE | The ability is being created. |
| 1 | ABILITY_STATE_READY | The ability has been created. |
| 2 | ABILITY_STATE_FOREGROUND | The ability is running in the foreground. |
| 3 | ABILITY_STATE_FOCUS | The ability has focus. |
| 4 | ABILITY_STATE_BACKGROUND | The ability is running in the background. |
| 5 | ABILITY_STATE_TERMINATED | The ability is terminated. |
| 8 | ABILITY_STATE_CONNECTED | The background service is connected to the client.|
| 9 | ABILITY_STATE_DISCONNECTED | The background service is disconnected from the client.|
#### Ability Types
| Value | Status | Description |
| ---- | ------- | --------------------- |
| 0 | UNKNOWN | Unknown type. |
| 1 | PAGE | Ability that has the UI. |
| 2 | SERVICE | Ability that provides the background service.|
......@@ -38,11 +38,11 @@ Registers a listener to monitor the ability lifecycle of the application.
**Example**
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from '@ohos.app.ability.UIAbility';
var lifecycleId;
export default class MyAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
let AbilityLifecycleCallback = {
......@@ -105,11 +105,11 @@ Deregisters the listener that monitors the ability lifecycle of the application.
**Example**
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from '@ohos.app.ability.UIAbility';
var lifecycleId;
export default class MyAbility extends Ability {
export default class EntryAbility extends UIAbility {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
console.log("stage applicationContext: " + JSON.stringify(applicationContext));
......@@ -143,11 +143,11 @@ Registers a listener for system environment changes. This API uses an asynchrono
**Example**
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from '@ohos.app.ability.UIAbility';
var callbackId;
export default class MyAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
globalThis.applicationContext = this.context.getApplicationContext();
......@@ -155,6 +155,9 @@ export default class MyAbility extends Ability {
onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config));
},
onMemoryLevel(level){
console.log("onMemoryLevel level:" + level);
}
}
// 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext;
......@@ -183,11 +186,11 @@ Deregisters the listener for system environment changes. This API uses an asynch
**Example**
```ts
import Ability from "@ohos.application.Ability";
import UIAbility from '@ohos.app.ability.UIAbility';
var callbackId;
export default class MyAbility extends Ability {
export default class EntryAbility extends UIAbility {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
......
# ApplicationStateObserver
The **ApplicationStateObserver** module defines the listener to observe the application state.
The **ApplicationStateObserver** module defines an observer to listen for application state changes. It can be used as an input parameter in [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8) to listen for lifecycle changes of the current application.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- |
| onForegroundApplicationChanged<sup>8+</sup> | AsyncCallback\<void> | Yes | No | Callback invoked when the foreground or background state of an application changes. |
| onAbilityStateChanged<sup>8+</sup> | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. |
| onProcessCreated<sup>8+</sup> | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. |
| onProcessDied<sup>8+</sup> | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. |
| onProcessStateChanged<sup>8+</sup> | AsyncCallback\<void> | Yes | No | Callback invoked when the process state is changed. |
| Name | | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- |
| onForegroundApplicationChanged<sup>8+</sup> | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\<void> | Yes | No | Callback invoked when the foreground or background state of an application changes. |
| onAbilityStateChanged<sup>8+</sup> | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. |
| onProcessCreated<sup>8+</sup> | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. |
| onProcessDied<sup>8+</sup> | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. |
| onProcessStateChanged<sup>8+</sup> | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\<void> | Yes | No | Callback invoked when the process state is changed. |
**Example**
```ts
......
# BaseContext
The abstract class **BaseContext** specifies whether its child class **Context** is used for the stage model or FA model.
**BaseContext** is an abstract class that specifies whether a child class **Context** is used for the stage model or FA model. It is the parent class for all types of **Context**.
> **NOTE**
>
......@@ -10,14 +10,19 @@ The abstract class **BaseContext** specifies whether its child class **Context**
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| stageMode | boolean | Yes | Yes | Whether the context is used for the stage model.|
| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.<br>**true**: used for the stage model.<br>**false**: used for the FA model.|
**Example**
```ts
class MyContext extends BaseContext {
constructor(stageMode) {
this.stageMode = stageMode;
}
Take the stage model as an example. You can access the **stageMode** field through **UIAbilityContext**.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
// EntryAbility onCreate, isStageMode: true
console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode);
}
```
}
```
# Context
The **Context** module provides context for abilities or applications. It allows access to application-specific resources, as well as permission requests and verification.
The **Context** module provides context for abilities or applications. It allows access to application-specific resources.
> **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.
> - 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.
## Attributes
......@@ -13,8 +13,8 @@ The **Context** module provides context for abilities or applications. It allows
| Name | Type | Readable | Writable | Description |
| ----------- | ------ | ---- | ---- | ------- |
| resourceManager | resmgr.ResourceManager | Yes | No | Object for resource management. |
| applicationInfo | ApplicationInfo | Yes | No | Application information.|
| resourceManager | resmgr.[ResourceManager](js-apis-resource-manager.md) | Yes | No | Object for resource management. |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information.|
| cacheDir | string | Yes | No | Cache directory.|
| tempDir | string | Yes | No | Temporary directory.|
| filesDir | string | Yes | No | File directory.|
......@@ -25,20 +25,21 @@ The **Context** module provides context for abilities or applications. It allows
| eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.|
| area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.|
## Context.createBundleContext
createBundleContext(bundleName: string): Context;
Creates the context based on the bundle name.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ------------- |
| bundleName | string | Yes | Bundle name of the application.|
| bundleName | string | Yes | Bundle name.|
**Return value**
......@@ -46,10 +47,24 @@ Creates the context based on the bundle name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let bundleContext = this.context.createBundleContext("com.example.test");
let bundleContext;
try {
bundleContext = this.context.createBundleContext("com.example.test");
} catch (error) {
console.log('createBundleContext failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
## Context.createModuleContext
......@@ -72,10 +87,24 @@ Creates the context based on the module name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let moduleContext = this.context.createModuleContext("entry");
let moduleContext;
try {
moduleContext = this.context.createModuleContext("entry");
} catch (error) {
console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
createModuleContext(bundleName: string, moduleName: string): Context;
......@@ -88,7 +117,7 @@ Creates the context based on the bundle name and module name.
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ------------- |
| bundleName | string | Yes | Bundle name of the application.|
| bundleName | string | Yes | Bundle name.|
| moduleName | string | Yes | Module name.|
**Return value**
......@@ -97,17 +126,31 @@ Creates the context based on the bundle name and module name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let moduleContext = this.context.createModuleContext("com.example.test", "entry");
let moduleContext;
try {
moduleContext = this.context.createModuleContext("com.example.test", "entry");
} catch (error) {
console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
## Context.getApplicationContext
getApplicationContext(): ApplicationContext;
Obtains the application context.
Obtains the context of this application.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -115,12 +158,18 @@ Obtains the application context.
| Type| Description|
| -------- | -------- |
| Context | Application context obtained.|
| [ApplicationContext](js-apis-inner-application-applicationContext.md) | Application context obtained.|
**Example**
```ts
let applicationContext = this.context.getApplicationContext();
let applicationContext;
try {
applicationContext = this.context.getApplicationContext();
} catch (error) {
console.log('getApplicationContext failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
## AreaMode
......@@ -131,5 +180,5 @@ Enumerates the areas in which the file to be access can be located.
| 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).|
# ContinueCallback
The **ContinueCallback** module defines the callback invoked when the mission continuation is complete.
The **ContinueCallback** module defines the callback function that indicates the result of mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission).
## ContinueCallback.onContinueDone
onContinueDone(result: number): void;
Called when the mission continuation is complete.
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Type | Readable | Writable | Description |
| --------------------- | -------- | ---- | ---- | ------------------ |
| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| result | number | No| Mission continuation result.|
**Example**
```ts
import distributedMissionManager from '@ohos.distributedMissionManager';
import distributedMissionManager from '@ohos.distributedMissionManager'
let continueDeviceInfo = {
srcDeviceId: "123",
......@@ -26,12 +34,13 @@ The **ContinueCallback** module defines the callback invoked when the mission co
onContinueDone(result) {
console.log('onContinueDone, result: ' + JSON.stringify(result));
}
}
};
distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => {
if (error.code != 0) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
if (error && error.code) {
console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
console.info('continueMission finished')
console.log('continueMission finished');
})
```
# ContinueDeviceInfo
The **ContinueDeviceInfo** module defines the parameters required for mission continuation.
The **ContinueDeviceInfo** module defines the parameters required for initiating mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
......@@ -14,7 +14,7 @@ The **ContinueDeviceInfo** module defines the parameters required for mission co
**Example**
```ts
import distributedMissionManager from '@ohos.distributedMissionManager';
import distributedMissionManager from '@ohos.distributedMissionManager'
let continueDeviceInfo = {
srcDeviceId: "123",
......@@ -29,12 +29,13 @@ The **ContinueDeviceInfo** module defines the parameters required for mission co
onContinueDone(result) {
console.log('onContinueDone, result: ' + JSON.stringify(result));
}
}
};
distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => {
if (error.code != 0) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
if (error && error.code) {
console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
console.info('continueMission finished')
console.log('continueMission finished');
})
```
# ErrorObserver
The **ErrorObserver** module defines the listener to observe errors.
The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application.
## onUnhandledException
## ErrorObserver.onUnhandledException
onUnhandledException(errMsg: string): void;
......@@ -19,12 +19,18 @@ Called when an unhandled exception occurs in the JS runtime.
**Example**
```ts
import errorManager from '@ohos.application.errorManager';
import errorManager from '@ohos.app.ability.errorManager'
let observer = {
onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ' + JSON.stringify(errorMsg));
console.log('HXW onUnhandledException, errorMsg: ', errorMsg);
}
}
errorManager.registerErrorObserver(observer)
try {
errorManager.on("error", observer);
} catch (error) {
console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
......@@ -4,21 +4,23 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri
> **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.
> - 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 any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance.
Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance.
```ts
import Ability from '@ohos.application.Ability';
export default class MainAbility extends Ability {
func1(){
console.log("func1 is called");
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
eventFunc(){
console.log("eventFunc is called");
}
onForeground() {
this.context.eventHub.on("123", this.func1);
this.context.eventHub.on("myEvent", this.eventFunc);
}
}
```
......@@ -40,32 +42,35 @@ Subscribes to an event.
**Example**
```ts
import Ability from '@ohos.application.Ability';
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.eventHub.on("123", this.func1);
this.context.eventHub.on("123", () => {
console.log("call anonymous func 1");
this.context.eventHub.on("myEvent", this.eventFunc);
// Anonymous functions can be used to subscribe to events.
this.context.eventHub.on("myEvent", () => {
console.log("call anonymous eventFunc");
});
// Result
// func1 is called
// call anonymous func 1
this.context.eventHub.emit("123");
}
func1() {
console.log("func1 is called");
}
// eventFunc is called
// call anonymous eventFunc
this.context.eventHub.emit("myEvent");
}
```
eventFunc() {
console.log("eventFunc is called");
}
}
```
## EventHub.off
off(event: string, callback?: Function): void;
Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event.
Unsubscribes from an event.
- If **callback** is specified, this API unsubscribes from the given event with the specified callback.
- If **callback** is not specified, this API unsubscribes from the given event with all callbacks.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -74,30 +79,31 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| event | string | Yes| Event name.|
| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.|
| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.|
**Example**
```ts
import Ability from '@ohos.application.Ability';
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.eventHub.on("123", this.func1);
this.context.eventHub.off("123", this.func1); // Unsubscribe from func1.
this.context.eventHub.on("123", this.func1);
this.context.eventHub.on("123", this.func2);
this.context.eventHub.off("123"); // Unsubscribe from func1 and func2.
}
func1() {
console.log("func1 is called");
}
func2() {
console.log("func2 is called");
this.context.eventHub.on("myEvent", this.eventFunc1);
this.context.eventHub.off("myEvent", this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1.
this.context.eventHub.on("myEvent", this.eventFunc1);
this.context.eventHub.on("myEvent", this.eventFunc2);
this.context.eventHub.off("myEvent"); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2).
}
eventFunc1() {
console.log("eventFunc1 is called");
}
```
eventFunc2() {
console.log("eventFunc2 is called");
}
}
```
## EventHub.emit
......@@ -116,24 +122,25 @@ Triggers an event.
**Example**
```ts
import Ability from '@ohos.application.Ability';
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.eventHub.on("123", this.func1);
this.context.eventHub.on("myEvent", this.eventFunc);
// Result
// func1 is called,undefined,undefined
this.context.eventHub.emit("123");
// eventFunc is called,undefined,undefined
this.context.eventHub.emit("myEvent");
// Result
// func1 is called,1,undefined
this.context.eventHub.emit("123", 1);
// eventFunc is called,1,undefined
this.context.eventHub.emit("myEvent", 1);
// Result
// func1 is called,1,2
this.context.eventHub.emit("123", 1, 2);
}
func1(a, b) {
console.log("func1 is called," + a + "," + b);
// eventFunc is called,1,2
this.context.eventHub.emit("myEvent", 1, 2);
}
eventFunc(argOne, argTwo) {
console.log("eventFunc is called," + argOne + "," + argTwo);
}
```
}
```
......@@ -61,10 +61,11 @@ export default class TheServiceExtension extends ServiceExtension {
Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry.
```ts
import Ability from '@ohos.app.ability.Ability'
export default class MainAbility extends Ability {
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
console.log("[Demo] EntryAbility onCreate");
let wantExt = {
deviceId: "",
bundleName: "com.example.TheServiceExtension",
......
# ExtensionRunningInfo
The **ExtensionRunningInfo** module provides running information and states for Extension abilities.
The **ExtensionRunningInfo** module encapsulates ExtensionAbility running information, which can be obtained through [getExtensionRunningInfos](js-apis-app-ability-abilityManager.md#getextensionrunninginfos).
> **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 are system APIs and cannot be called by third-party applications.
> - 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.
> - This module is marked as @systemapi and not visible to third-party applications.
## Usage
The Extension ability running information is obtained through an **abilityManager** instance.
Import the **abilityManager** module and obtain the ExtensionAbility running information by calling the method in the **abilityManager** module.
## Attributes
......@@ -17,21 +17,28 @@ The Extension ability running information is obtained through an **abilityManage
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| extension | ElementName | Yes| No| Information that matches an Extension ability.|
| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.|
| pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID.|
| uid | number | Yes| No| UID of the application.|
| processName | string | Yes| No| Process name.|
| startTime | number | Yes| No| Start time of the Extension ability.|
| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.|
| clientPackage | Array&lt;String&gt; | Yes| No| Names of all packages in the process.|
| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md) | Yes| No| Extension ability type.|
| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.|
**Example**
```ts
import abilityManager from '@ohos.application.abilityManager';
let upperLimit=1;
abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
for (let i=0; i<data.length; i++) {
import abilityManager from '@ohos.app.ability.abilityManager'
var upperLimit = 1;
function getExtensionInfos() {
abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => {
if (error && error.code) {
console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
return;
}
for (let i = 0; i < data.length; i++) {
let extensionRunningInfo = data[i];
console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension));
console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid));
......@@ -41,5 +48,6 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage));
console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type));
}
});
});
}
```
# FormExtensionContext
The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities.
The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for FormExtensionAbilities.
You can use the APIs of this module to start Form Extension abilities.
You can use the APIs of this module to start FormExtensionAbilities.
> **NOTE**
>
......@@ -11,21 +11,24 @@ You can use the APIs of this module to start Form Extension abilities.
## Usage
Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance.
Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtensionAbility** instance.
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm() {
onAddForm(want) {
let formContext = this.context; // Obtain a FormExtensionContext instance.
// ...
let dataObj1 = {
temperature:"11c",
"time":"11:00"
temperature: "11c",
"time": "11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
}
};
```
## startAbility
......@@ -48,23 +51,29 @@ Starts an ability. This API uses an asynchronous callback to return the result.
**Example**
```ts
var want = {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
// Call startAbility() when the message event is triggered.
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
let want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want, (error, data) => {
abilityName: "EntryAbility",
parameters: {
"message": message
}
};
this.context.startAbility(want, (error, data) => {
if (error) {
console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error));
} else {
console.log(`FormExtensionContext startAbility success`);
console.log('FormExtensionContext startAbility success');
}
});
}
})
};
```
## startAbility
......@@ -87,24 +96,30 @@ Starts an ability. This API uses a promise to return the result.
| Type | Description |
| ------------ | ---------------------------------- |
| Promise&lt;void&lt; | Promise that returns no value.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
var want = {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
// Call startAbility() when the message event is triggered.
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
let want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want).then(() => {
abilityName: "EntryAbility",
parameters: {
"message": message
}
};
this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
}).catch((error) => {
console.info("StartAbility failed");
});
});
}
};
```
# MissionCallbacks
# MissionCallback
The **MissionCallbacks** module defines the callbacks that can be registered as a mission status listener.
The **MissionCallback** module defines the callbacks invoked after synchronization starts. These callbacks can be used as input parameters in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Template | Readable | Writable | Description |
| --------------------- | -------- | ---- | ---- | ------------------ |
| notifyMissionsChanged | function | Yes | No | Callback used to notify the mission change event and return the device ID. |
| notifySnapshot | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID.|
| notifyNetDisconnect | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.|
| Name | Template | Readable| Writable| Description |
| ---------------------------------------------------- | -------- | ---- | ---- | ---------------------------------- |
| notifyMissionsChanged(deviceId: string) | function | Yes | No | Callback used to notify the mission change event and return the device ID. |
| notifySnapshot(deviceId: string, mission: number) | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID. |
| notifyNetDisconnect(deviceId: string, state: number) | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.|
**Example**
```ts
......@@ -21,12 +21,12 @@ let missionCallback = {
notifyMissionsChanged: function (deviceId) {
console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId));
},
notifySnapshot: function (mission, deviceId) {
console.log("notifySnapshot mission: " + JSON.stringify(mission));
notifySnapshot: function (deviceId, mission) {
console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId));
console.log("notifySnapshot mission: " + JSON.stringify(mission));
},
notifyNetDisconnect: function (mission, state) {
console.log("notifyNetDisconnect mission: " + JSON.stringify(mission));
notifyNetDisconnect: function (deviceId, state) {
console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId));
console.log("notifyNetDisconnect state: " + JSON.stringify(state));
}
};
......
# MissionDeviceInfo
The **MissionDeviceInfo** module defines the parameters required for registering a listener.
The **MissionDeviceInfo** module defines the parameters required for registering a listener. It can be used as an input parameter in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
......
# MissionInfo
The **MissionInfo** module defines the mission information of an ability.
The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
......@@ -19,16 +19,27 @@ The **MissionInfo** module defines the mission information of an ability.
**Example**
```ts
import missionManager from '@ohos.application.missionManager'
import missionManager from '@ohos.app.ability.missionManager'
missionManager.getMissionInfo("12345", 1, (error, data) => {
console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId));
console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState));
console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState));
console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp));
console.info('getMissionInfo want is:' + JSON.stringify(data.want));
console.info('getMissionInfo label is:' + JSON.stringify(data.label));
console.info('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath));
console.info('getMissionInfo continuable is:' + JSON.stringify(data.continuable));
});
try {
missionManager.getMissionInfo("", 1, (error, data) => {
if (error.code) {
// Process service logic errors.
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log('getMissionInfo missionId is:' + JSON.stringify(data.missionId));
console.log('getMissionInfo runningState is:' + JSON.stringify(data.runningState));
console.log('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState));
console.log('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp));
console.log('getMissionInfo want is:' + JSON.stringify(data.want));
console.log('getMissionInfo label is:' + JSON.stringify(data.label));
console.log('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath));
console.log('getMissionInfo continuable is:' + JSON.stringify(data.continuable));
});
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
# MissionParameter
The **MissionParameter** module defines the parameters required for mission synchronization.
The **MissionParameter** module defines the parameters required for mission synchronization. It can be used an input parameter in [startSyncRemoteMissions](js-apis-distributedMissionManager.md#distributedmissionmanagerstartsyncremotemissions).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
......
# MissionSnapshot
The **MissionSnapshot** module provides the mission snapshot information of an ability.
The **MissionSnapshot** module defines the snapshot of a mission. The snapshot can be obtained through [getMissionSnapShot](js-apis-app-ability-missionManager.md#missionmanagergetmissionsnapshot).
> **NOTE**
>
......@@ -11,7 +11,7 @@ The **MissionSnapshot** module provides the mission snapshot information of an a
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| ability | ElementName | Yes| Yes| Information that matches an ability.|
| ability | ElementName | Yes| Yes| Ability information of the mission.|
| snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.|
## How to Use
......@@ -20,19 +20,33 @@ The mission snapshot information can be obtained by using **getMissionSnapShot**
**Example**
```ts
import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image';
import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => {
console.log("getMissionInfos is called, error.code = " + error.code);
import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image';
import missionManager from '@ohos.app.ability.missionManager';
try {
missionManager.getMissionInfos("", 10, (error, missions) => {
if (error.code) {
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) +
"error.message:" + JSON.stringify(error.message));
return;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.getMissionSnapShot("", id, (error, snapshot) => {
console.log("getMissionSnapShot is called, error.code = " + error.code);
missionManager.getMissionSnapShot("", id, (err, snapshot) => {
if (err.code) {
console.log("getMissionInfos failed, err.code:" + JSON.stringify(err.code) +
"err.message:" + JSON.stringify(err.message));
return;
}
// Carry out normal service processing.
console.log("bundleName = " + snapshot.ability.bundleName);
})
})
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
# ProcessData
The **ProcessData** module defines process data.
The **ProcessData** module defines process data. If a lifecycle change listener is registered by calling [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8), the **onProcessCreated** callback in [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) is invoked when the lifecycle of an application or ability changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -10,9 +10,10 @@ The **ProcessData** module defines process data.
| ----------------------- | ---------| ---- | ---- | ------------------------- |
| pid<sup>8+</sup> | number | Yes | No | Process ID. |
| bundleName<sup>8+</sup> | string | Yes | No | Bundle name of the application. |
| uid<sup>8+</sup> | number | Yes | No | User ID. |
| isContinuousTask<sup>9+</sup> | boolean | Yes | No | Whether the process is a continuous task. |
| isKeepAlive<sup>9+</sup> | boolean | Yes | No | Whether the process remains active. |
| uid<sup>8+</sup> | number | Yes | No | UID of the application. |
| isContinuousTask<sup>9+</sup> | boolean | Yes | No | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. |
| isKeepAlive<sup>9+</sup> | boolean | Yes | No | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. |
| state<sup>9+</sup> | number | Yes | No | Application state. The value can be **0** (newly created), **2** (foreground), **4** (background), or **5** (terminated). |
**Example**
```ts
......
# ProcessRunningInfo
The **ProcessRunningInfo** module provides process running information.
The **ProcessRunningInfo** module defines the running information of a process.
> **NOTE**
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation<sup>9+</sup>](js-apis-inner-application-processRunningInformation.md) instead.
......@@ -19,12 +19,13 @@ The **ProcessRunningInfo** module provides process running information.
## Usage
The process running information is obtained through [getProcessRunningInfos](js-apis-application-appManager.md##appManager.getProcessRunningInfos<sup>(deprecated)</sup>).
The process running information is obtained by using [getProcessRunningInfos](js-apis-application-appManager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**.
**Example**
```ts
import appManager from '@ohos.application.appManager';
app.getProcessRunningInfos().then((data) => {
appManager.getProcessRunningInfos().then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
......
# ProcessRunningInformation
The **ProcessRunningInformation** module provides process running information.
The **ProcessRunningInformation** module defines the running information of a process.
> **NOTE**
>
......@@ -8,12 +8,13 @@ The **ProcessRunningInformation** module provides process running information.
## How to Use
The process running information is obtained through [appManager](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9).
The process running information is obtained through [getProcessRunningInformation](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9) in **appManager**.
```ts
import appManager from '@ohos.application.appManager';
appManager.getProcessRunningInformation((error,data) => {
console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data));
appManager.getProcessRunningInformation((error, data) => {
console.log("error: " + error.code + " data: " + JSON.stringify(data));
});
```
......
# ServiceExtensionContext
The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities.
The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for ServiceExtensionAbilities.
You can use the APIs of this module to start, terminate, connect, and disconnect abilities.
......@@ -17,9 +17,9 @@ Before using the **ServiceExtensionContext** module, you must define a child cla
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
let context = undefined;
class MainAbility extends ServiceExtensionAbility {
class EntryAbility extends ServiceExtensionAbility {
onCreate() {
context = this.context;
context = this.context; // Obtain a ServiceExtensionContext instance.
}
}
```
......@@ -36,10 +36,10 @@ Starts an ability. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
**Error codes**
......@@ -103,16 +103,16 @@ Starts an ability. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -214,8 +214,8 @@ Starts an ability with the start options specified. This API uses an asynchronou
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var options = {
windowMode: 0
......@@ -245,6 +245,11 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
Starts an ability with the account ID specified. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -287,8 +292,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -316,6 +321,11 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
Starts an ability with the account ID and start options specified. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -359,8 +369,8 @@ Starts an ability with the account ID and start options specified. This API uses
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -392,6 +402,11 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
Starts an ability with the account ID specified. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -406,9 +421,9 @@ Starts an ability with the account ID specified. This API uses a promise to retu
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -440,8 +455,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -470,7 +485,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu
startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability. This API uses an asynchronous callback to return the result.
Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -505,8 +520,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -531,7 +546,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
startServiceExtensionAbility(want: Want): Promise\<void>;
Starts a new Service Extension ability. This API uses a promise to return the result.
Starts a new ServiceExtensionAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -545,9 +560,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -571,8 +586,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -597,9 +612,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re
startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result.
Starts a new ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -637,8 +652,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -664,9 +679,9 @@ Starts a new Service Extension ability with the account ID specified. This API u
startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result.
Starts a new ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -681,9 +696,9 @@ Starts a new Service Extension ability with the account ID specified. This API u
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -708,8 +723,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -735,7 +750,7 @@ Starts a new Service Extension ability with the account ID specified. This API u
stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -767,8 +782,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -793,7 +808,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn
stopServiceExtensionAbility(want: Want): Promise\<void>;
Stops a Service Extension ability in the same application. This API uses a promise to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -807,9 +822,9 @@ Stops a Service Extension ability in the same application. This API uses a promi
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -830,8 +845,8 @@ Stops a Service Extension ability in the same application. This API uses a promi
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
try {
......@@ -856,9 +871,9 @@ Stops a Service Extension ability in the same application. This API uses a promi
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -892,8 +907,8 @@ Stops a Service Extension ability in the same application with the account ID sp
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -919,9 +934,9 @@ Stops a Service Extension ability in the same application with the account ID sp
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result.
Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -936,9 +951,9 @@ Stops a Service Extension ability in the same application with the account ID sp
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -960,8 +975,8 @@ Stops a Service Extension ability in the same application with the account ID sp
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
......@@ -995,9 +1010,9 @@ Terminates this ability. This API uses an asynchronous callback to return the re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
**Error codes**
......@@ -1037,9 +1052,9 @@ Terminates this ability. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -1069,7 +1084,7 @@ Terminates this ability. This API uses a promise to return the result.
connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
Connects this ability to a Service ability.
Connects this ability to a ServiceAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1077,16 +1092,16 @@ Connects this ability to a Service ability.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | A number, based on which the connection will be interrupted.|
| Type| Description|
| -------- | -------- |
| number | A number, based on which the connection will be interrupted.|
**Error codes**
......@@ -1165,8 +1180,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
};
var accountId = 100;
var options = {
......@@ -1189,7 +1204,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback&lt;void&gt;): void;
Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result.
Disconnects this ability from the ServiceAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1197,10 +1212,10 @@ Disconnects this ability from the Service ability. This API uses an asynchronous
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.|
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.|
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
**Error codes**
......@@ -1241,7 +1256,7 @@ Disconnects this ability from the Service ability. This API uses an asynchronous
disconnectServiceExtensionAbility(connection: number): Promise&lt;void&gt;;
Disconnects this ability from the Service ability. This API uses a promise to return the result.
Disconnects this ability from the ServiceAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1249,15 +1264,15 @@ Disconnects this ability from the Service ability. This API uses a promise to re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
......@@ -1300,6 +1315,11 @@ startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
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.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -1341,7 +1361,7 @@ Starts an ability in the foreground or background and obtains the caller object
var wantBackground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: ""
};
......@@ -1372,7 +1392,7 @@ Starts an ability in the foreground or background and obtains the caller object
var wantForeground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
abilityName: "EntryAbility",
deviceId: "",
parameters: {
"ohos.aafwk.param.callAbilityToForeground": true
......
......@@ -25,7 +25,7 @@ let cmd = "cmd";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => {
console.info("executeShellCommand callback, failed: ", err);
console.info("executeShellCommand callback, success: ", data);
console.info("executeShellCommand callback, result: ", err);
console.info("executeShellCommand callback, data: ", data);
});
```
# UIAbilityContext
The **UIAbilityContext** module, inherited from **Context**, implements the context for abilities.
This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box.
**UIAbilityContext**, inherited from [Context](js-apis-inner-application-context.md), provides the context environment for [UIAbility](js-apis-app-ability-uiAbility.md). **UIAbilityContext** provides UIAbility-related configuration and APIs for operating UIAbilities and ServiceExtensionAbilities. For example, you can use the APIs to start a UIAbility, terminate a UIAbility to which the UIAbilityContext belongs, and start, terminate, connect to, or disconnect from a ServiceExtensionAbility.
> **NOTE**
>
......@@ -15,16 +13,24 @@ This module provides APIs for accessing ability-specific resources. You can use
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.|
| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.|
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration information.|
| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| UIAbility information.|
| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| HAP information.|
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| UIAbility configuration, such as the language and color mode.|
> **NOTE**
> - In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** capabilities on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
## AbilityContext.startAbility
## UIAbilityContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -79,18 +85,22 @@ Starts an ability. This API uses an asynchronous callback to return the result.
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbility
## UIAbilityContext.startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability with the start options specified. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -103,7 +113,7 @@ Starts an ability with the start options specified. This API uses an asynchronou
**Error codes**
| ID| Error Message
| ID| Error Message|
| ------- | -------------------------------- |
| 201 | The application does not have permission to call the interface. |
| 401 | Invalid input parameter. |
......@@ -130,7 +140,7 @@ Starts an ability with the start options specified. This API uses an asynchronou
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var options = {
......@@ -150,17 +160,22 @@ Starts an ability with the start options specified. This API uses an asynchronou
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbility
## UIAbilityContext.startAbility
startAbility(want: Want, options?: StartOptions): Promise&lt;void&gt;;
Starts an ability. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -213,7 +228,7 @@ Starts an ability. This API uses a promise to return the result.
try {
this.context.startAbility(want, options)
.then((data) => {
.then(() => {
// Carry out normal service processing.
console.log('startAbility succeed');
})
......@@ -224,17 +239,21 @@ Starts an ability. This API uses a promise to return the result.
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResult
## UIAbilityContext.startAbilityForResult
startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void;
Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -274,7 +293,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
......@@ -287,21 +306,25 @@ Starts an ability. This API uses an asynchronous callback to return the result w
return;
}
// Carry out normal service processing.
console.log("startAbilityForResult succeed, result.resultCode = " +
result.resultCode)
console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode)
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResult
## UIAbilityContext.startAbilityForResult
startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback&lt;AbilityResult&gt;): void;
Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated.
Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -342,7 +365,7 @@ Starts an ability with the start options specified. This API uses an asynchronou
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var options = {
......@@ -358,22 +381,26 @@ Starts an ability with the start options specified. This API uses an asynchronou
return;
}
// Carry out normal service processing.
console.log("startAbilityForResult succeed, result.resultCode = " +
result.resultCode)
console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode)
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResult
## UIAbilityContext.startAbilityForResult
startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityResult&gt;;
Starts an ability. This API uses a promise to return the result when the ability is terminated.
Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. 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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -419,8 +446,8 @@ Starts an ability. This API uses a promise to return the result when the ability
```ts
var want = {
bundleName: "com.example.myapp",
abilityName: "MyAbility"
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var options = {
windowMode: 0,
......@@ -439,18 +466,23 @@ Starts an ability. This API uses a promise to return the result when the ability
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResultWithAccount
## UIAbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void;
Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed.
Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated.
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -461,8 +493,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<AbilityResult\> | Yes| Callback used to return the result.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| callback | AsyncCallback&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Yes| Callback used to return the result.|
**Error codes**
......@@ -494,7 +526,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -509,23 +541,28 @@ Starts an ability. This API uses an asynchronous callback to return the result w
}
// Carry out normal service processing.
console.log("startAbilityForResultWithAccount succeed, result.resultCode = " +
result.resultCode)
result.resultCode + ' result.want = ' + JSON.stringify(result.want))
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResultWithAccount
## UIAbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed.
Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated.
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -536,9 +573,9 @@ Starts an ability with the start options specified. This API uses an asynchronou
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
| callback | AsyncCallback\<void\> | Yes| Callback invoked when the ability is terminated.|
**Error codes**
......@@ -570,7 +607,7 @@ Starts an ability with the start options specified. This API uses an asynchronou
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -579,7 +616,7 @@ Starts an ability with the start options specified. This API uses an asynchronou
};
try {
this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => {
this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => {
if (error.code) {
// Process service logic errors.
console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) +
......@@ -587,24 +624,28 @@ Starts an ability with the start options specified. This API uses an asynchronou
return;
}
// Carry out normal service processing.
console.log("startAbilityForResultWithAccount succeed, result.resultCode = " +
result.resultCode)
console.log("startAbilityForResultWithAccount succeed")
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityForResultWithAccount
## UIAbilityContext.startAbilityForResultWithAccount
startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult\>;
Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed.
Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -615,14 +656,14 @@ Starts an ability with the start options specified. This API uses a promise to r
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;AbilityResult&gt; | Promise used to return the result.|
| Promise&lt;[AbilityResult](js-apis-inner-ability-abilityResult.md)&gt; | Promise used to return the ability result when the ability is terminated.|
**Error codes**
......@@ -654,7 +695,7 @@ Starts an ability with the start options specified. This API uses a promise to r
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -676,15 +717,15 @@ Starts an ability with the start options specified. This API uses a promise to r
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startServiceExtensionAbility
## UIAbilityContext.startServiceExtensionAbility
startServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability. This API uses an asynchronous callback to return the result.
Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -694,7 +735,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -719,8 +760,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
try {
......@@ -736,16 +777,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startServiceExtensionAbility
## UIAbilityContext.startServiceExtensionAbility
startServiceExtensionAbility(want: Want): Promise\<void>;
Starts a new Service Extension ability. This API uses a promise to return the result.
Starts a ServiceExtensionAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -755,7 +796,7 @@ Starts a new Service Extension ability. This API uses a promise to return the re
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
**Error codes**
......@@ -779,13 +820,13 @@ Starts a new Service Extension ability. This API uses a promise to return the re
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
try {
this.context.startServiceExtensionAbility(want)
.then((data) => {
.then(() => {
// Carry out normal service processing.
console.log('startServiceExtensionAbility succeed');
})
......@@ -796,18 +837,18 @@ Starts a new Service Extension ability. This API uses a promise to return the re
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startServiceExtensionAbilityWithAccount
## UIAbilityContext.startServiceExtensionAbilityWithAccount
startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result.
Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -817,8 +858,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -840,8 +881,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var accountId = 100;
......@@ -858,18 +899,18 @@ Starts a new Service Extension ability with the account ID specified. This API u
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startServiceExtensionAbilityWithAccount
## UIAbilityContext.startServiceExtensionAbilityWithAccount
startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result.
Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -880,7 +921,7 @@ Starts a new Service Extension ability with the account ID specified. This API u
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
**Error codes**
......@@ -905,8 +946,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var accountId = 100;
......@@ -923,15 +964,15 @@ Starts a new Service Extension ability with the account ID specified. This API u
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.stopServiceExtensionAbility
## UIAbilityContext.stopServiceExtensionAbility
stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -941,7 +982,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -963,8 +1004,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
try {
......@@ -980,16 +1021,16 @@ Stops a Service Extension ability in the same application. This API uses an asyn
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.stopServiceExtensionAbility
## UIAbilityContext.stopServiceExtensionAbility
stopServiceExtensionAbility(want: Want): Promise\<void>;
Stops a Service Extension ability in the same application. This API uses a promise to return the result.
Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -999,7 +1040,7 @@ Stops a Service Extension ability in the same application. This API uses a promi
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
**Error codes**
......@@ -1020,8 +1061,8 @@ Stops a Service Extension ability in the same application. This API uses a promi
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
try {
......@@ -1037,18 +1078,18 @@ Stops a Service Extension ability in the same application. This API uses a promi
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.stopServiceExtensionAbilityWithAccount
## UIAbilityContext.stopServiceExtensionAbilityWithAccount
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void;
Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result.
Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1058,8 +1099,8 @@ Stops a Service Extension ability in the same application with the account ID sp
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -1082,8 +1123,8 @@ Stops a Service Extension ability in the same application with the account ID sp
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var accountId = 100;
......@@ -1100,18 +1141,18 @@ Stops a Service Extension ability in the same application with the account ID sp
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.stopServiceExtensionAbilityWithAccount
## UIAbilityContext.stopServiceExtensionAbilityWithAccount
stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<void>;
Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result.
Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1121,8 +1162,8 @@ Stops a Service Extension ability in the same application with the account ID sp
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
**Error codes**
......@@ -1144,8 +1185,8 @@ Stops a Service Extension ability in the same application with the account ID sp
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var accountId = 100;
......@@ -1162,12 +1203,12 @@ Stops a Service Extension ability in the same application with the account ID sp
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.terminateSelf
## UIAbilityContext.terminateSelf
terminateSelf(callback: AsyncCallback&lt;void&gt;): void;
......@@ -1195,6 +1236,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re
**Example**
```ts
try {
this.context.terminateSelf((error) => {
if (error.code) {
// Process service logic errors.
......@@ -1205,10 +1247,15 @@ Terminates this ability. This API uses an asynchronous callback to return the re
// Carry out normal service processing.
console.log('terminateSelf succeed');
});
} catch (error) {
// Capture the synchronization parameter error.
console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
## AbilityContext.terminateSelf
## UIAbilityContext.terminateSelf
terminateSelf(): Promise&lt;void&gt;;
......@@ -1236,22 +1283,30 @@ Terminates this ability. This API uses a promise to return the result.
**Example**
```ts
this.context.terminateSelf().then((data) => {
try {
this.context.terminateSelf()
.then(() => {
// Carry out normal service processing.
console.log('terminateSelf succeed');
}).catch((error) => {
})
.catch((error) => {
// Process service logic errors.
console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
});
} catch (error) {
// Capture the synchronization parameter error.
console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
```
## AbilityContext.terminateSelfWithResult
## UIAbilityContext.terminateSelfWithResult
terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void;
Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1277,8 +1332,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab
```ts
var want = {
bundleName: "com.extreme.myapplication",
abilityName: "SecondAbility"
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
}
var resultCode = 100;
// AbilityResult information returned to the caller.
......@@ -1300,17 +1355,17 @@ Terminates this ability. This API uses an asynchronous callback to return the ab
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.terminateSelfWithResult
## UIAbilityContext.terminateSelfWithResult
terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;;
Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**.
Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1342,8 +1397,8 @@ Terminates this ability. This API uses a promise to return the ability result in
```ts
var want = {
bundleName: "com.extreme.myapplication",
abilityName: "SecondAbility"
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
}
var resultCode = 100;
// AbilityResult information returned to the caller.
......@@ -1365,16 +1420,16 @@ Terminates this ability. This API uses a promise to return the ability result in
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.connectServiceExtensionAbility
## UIAbilityContext.connectServiceExtensionAbility
connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability.
Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1384,8 +1439,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.|
| want | [Want](js-apis-application-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.|
**Return value**
......@@ -1410,13 +1465,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') }
onConnect(elementName, remote) {
console.log('----------- onConnect -----------')
},
onDisconnect(elementName) {
console.log('----------- onDisconnect -----------')
},
onFailed(code) {
console.log('----------- onFailed -----------')
}
}
var connection = null;
......@@ -1430,13 +1491,13 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to
```
## AbilityContext.connectServiceExtensionAbilityWithAccount
## UIAbilityContext.connectServiceExtensionAbilityWithAccount
connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number;
Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified.
Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template, with the account ID specified.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1447,8 +1508,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| Parameters for the connection.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.|
**Return value**
......@@ -1474,14 +1535,20 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
abilityName: "MainAbility"
bundleName: "com.example.myapplication",
abilityName: "ServiceExtensionAbility"
};
var accountId = 100;
var options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') }
onConnect(elementName, remote) {
console.log('----------- onConnect -----------')
},
onDisconnect(elementName) {
console.log('----------- onDisconnect -----------')
},
onFailed(code) {
console.log('----------- onFailed -----------')
}
}
var connection = null;
......@@ -1494,11 +1561,11 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
}
```
## AbilityContext.disconnectServiceExtensionAbility
## UIAbilityContext.disconnectServiceExtensionAbility
disconnectServiceExtensionAbility(connection: number): Promise\<void>;
Disconnects a connection. This API uses a promise to return the result.
Disconnects from a ServiceExtensionAbility. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1508,7 +1575,7 @@ Disconnects a connection. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Result code of the ability connection.|
| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.|
**Return value**
......@@ -1551,11 +1618,11 @@ Disconnects a connection. This API uses a promise to return the result.
}
```
## AbilityContext.disconnectServiceExtensionAbility
## UIAbilityContext.disconnectServiceExtensionAbility
disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\<void>): void;
Disconnects a connection. This API uses an asynchronous callback to return the result.
Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1565,7 +1632,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| connection | number | Yes| Result code of the ability connection.|
| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Error codes**
......@@ -1603,12 +1670,17 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
}
```
## AbilityContext.startAbilityByCall
## UIAbilityContext.startAbilityByCall
startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
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.
- The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -1690,13 +1762,18 @@ Starts an ability in the foreground or background and obtains the caller object
}
```
## AbilityContext.startAbilityWithAccount
## UIAbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void\>): void;
Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1707,7 +1784,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -1740,7 +1817,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -1764,13 +1841,18 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
```
## AbilityContext.startAbilityWithAccount
## UIAbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\<void\>): void;
Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1781,8 +1863,8 @@ Starts an ability with the account ID and start options specified. This API uses
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Error codes**
......@@ -1815,7 +1897,7 @@ Starts an ability with the account ID and start options specified. This API uses
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -1836,19 +1918,24 @@ Starts an ability with the account ID and start options specified. This API uses
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.startAbilityWithAccount
## UIAbilityContext.startAbilityWithAccount
startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void\>;
Starts an ability with the account ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
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 stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user)
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -1859,7 +1946,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.|
**Error codes**
......@@ -1892,7 +1979,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu
```ts
var want = {
deviceId: "",
bundleName: "com.extreme.test",
bundleName: "com.example.myapplication",
abilityName: "MainAbility"
};
var accountId = 100;
......@@ -1913,71 +2000,12 @@ Starts an ability with the account ID specified. This API uses a promise to retu
});
} catch (paramError) {
// Process input parameter errors.
console.log('error.code: ' + JSON.stringify(paramError.code) +
console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## AbilityContext.requestPermissionsFromUser
requestPermissionsFromUser(permissions: Array&lt;string&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void;
Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| Permissions to request.|
| callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)&gt; | Yes| Callback used to return the result.|
**Example**
```ts
var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
});
```
## AbilityContext.requestPermissionsFromUser
requestPermissionsFromUser(permissions: Array&lt;string&gt;) : Promise&lt;PermissionRequestResult&gt;;
Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| Permissions to request.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)&gt; | Promise used to return the result.|
**Example**
```ts
var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success:' + JSON.stringify(data));
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
```
## AbilityContext.setMissionLabel
## UIAbilityContext.setMissionLabel
setMissionLabel(label: string, callback:AsyncCallback&lt;void&gt;): void;
......@@ -1995,13 +2023,12 @@ Sets a label for this ability in the mission. This API uses an asynchronous call
**Example**
```ts
this.context.setMissionLabel("test",(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
this.context.setMissionLabel("test", (result) => {
console.log('setMissionLabel:' + JSON.stringify(result));
});
```
## AbilityContext.setMissionLabel
## UIAbilityContext.setMissionLabel
setMissionLabel(label: string): Promise&lt;void&gt;;
......@@ -2030,7 +2057,7 @@ Sets a label for this ability in the mission. This API uses a promise to return
console.log('failed:' + JSON.stringify(error));
});
```
## AbilityContext.setMissionIcon
## UIAbilityContext.setMissionIcon
setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void;
......@@ -2072,7 +2099,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
```
## AbilityContext.setMissionIcon
## UIAbilityContext.setMissionIcon
setMissionIcon(icon: image.PixelMap): Promise\<void>;
......@@ -2097,7 +2124,6 @@ Sets an icon for this ability in the mission. This API uses a promise to return
**Example**
```ts
import image from '@ohos.multimedia.image';
var imagePixelMap;
var color = new ArrayBuffer(0);
var initializationOptions = {
......@@ -2121,7 +2147,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return
console.log('-------------- setMissionIcon fail, err: -------------', err);
});
```
## AbilityContext.restoreWindowStage
## UIAbilityContext.restoreWindowStage
restoreWindowStage(localStorage: LocalStorage) : void;
......@@ -2142,7 +2168,7 @@ Restores the window stage data for this ability.
this.context.restoreWindowStage(storage);
```
## AbilityContext.isTerminating
## UIAbilityContext.isTerminating
isTerminating(): boolean;
......
# WantAgentInfo
The **WantAgentInfo** module defines the information required for triggering the WantAgent.
The **WantAgentInfo** module defines the information required for triggering a **WantAgent** object. The information can be used as an input parameter in [getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to obtain a specified **WantAgent** object.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -9,38 +9,5 @@ The **WantAgentInfo** module defines the information required for triggering the
| wants | Array\<Want\> | Yes | Array of all **Want** objects. |
| operationType | wantAgent.OperationType | Yes | Operation type. |
| requestCode | number | Yes | Request code defined by the user.|
| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-wantAgent.md#WantAgentFlags)> | No | Array of flags for using the **WantAgent** object. |
| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. |
| extraInfo | {[key: string]: any} | No | Extra information. |
**Example**
```ts
import wantAgent from '@ohos.wantAgent';
let wantAgentInfo = {
wants: [
{
deviceId: "",
bundleName: "com.example.apicoverhaptest",
abilityName: "com.example.apicoverhaptest.MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true.true,false}",
parameters: {
myKey0: 2222
}
}
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG],
extraInfo:{
"key": "value"
}
}
wantAgent.getWantAgent(wantAgentInfo).then((data) =>{
console.info("getWantAgent data: " + JSON.stringify(data));
}).catch((err) => {
console.error("getWantAgent err: " + JSON.stringify(err));
})
```
# PermissionRequestResult
The **PermissionRequestResult** module defines the result of a permission request. The result is returned when [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called to request permissions.
> **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.
## Attributes
**System capability**: SystemCapability.Security.AccessToken
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| No| Permissions requested.|
| authResults | Array&lt;number&gt; | Yes| No| Whether the requested permissions are granted. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite.|
## Usage
The permission request result is obtained through an **atManager** instance.
**Example**
```ts
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => {
console.info("data:" + JSON.stringify(data));
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
}).catch((err) => {
console.info("data:" + JSON.stringify(err));
})
} catch(err) {
console.log(`catch err->${JSON.stringify(err)}`);
}
```
<!--no_check-->
\ No newline at end of file
......@@ -707,7 +707,7 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback)
equal(agent: WantAgent, otherAgent: WantAgent): Promise\<boolean\>
Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result.
Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册