提交 d120e141 编写于 作者: G Gloria

Update docs against 14188+14620+14253+14202+14649+13561+14558+14342+14442+14939

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 a22b5149
...@@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export ...@@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export
## Modules to Import ## Modules to Import
```ts ```ts
import ability from '@ohos.ability.ability' import ability from '@ohos.ability.ability';
``` ```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
......
...@@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI. ...@@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI.
**Example** **Example**
```ts ```ts
let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); let id = dataUriUtils.getId('com.example.dataUriUtils/1221');
``` ```
...@@ -66,9 +66,9 @@ Attaches an ID to the end of a given URI. ...@@ -66,9 +66,9 @@ Attaches an ID to the end of a given URI.
```ts ```ts
let id = 1122; let id = 1122;
let uri = dataUriUtils.attachId( let uri = dataUriUtils.attachId(
"com.example.dataUriUtils", 'com.example.dataUriUtils',
id, id,
) );
``` ```
...@@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI. ...@@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI.
**Example** **Example**
```ts ```ts
let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") let uri = dataUriUtils.deleteId('com.example.dataUriUtils/1221');
``` ```
...@@ -127,7 +127,7 @@ Updates the ID in a given URI. ...@@ -127,7 +127,7 @@ Updates the ID in a given URI.
```ts ```ts
let id = 1122; let id = 1122;
let uri = dataUriUtils.updateId( let uri = dataUriUtils.updateId(
"com.example.dataUriUtils/1221", 'com.example.dataUriUtils/1221',
id id
) );
``` ```
...@@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab ...@@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab
## Modules to Import ## Modules to Import
```ts ```ts
import errorCode from '@ohos.ability.errorCode' import errorCode from '@ohos.ability.errorCode';
``` ```
## ErrorCode ## ErrorCode
......
...@@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the ...@@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the
| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | | 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. | | INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. |
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. The value must be an array of the string type. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_APP_ACCOUNT_AUTH <sup>9+</sup> | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_APP_ACCOUNT_AUTH <sup>9+</sup> | account.appAccount.action.auth | Action of providing the authentication service. |
| ACTION_MARKET_DOWNLOAD <sup>9+</sup> | 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_DOWNLOAD <sup>9+</sup> | 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. |
......
...@@ -21,14 +21,14 @@ Enumerates the ability states. This enum can be used together with [AbilityRunni ...@@ -21,14 +21,14 @@ Enumerates the ability states. This enum can be used together with [AbilityRunni
**System API**: This enum is an internal definition of 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| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.| | INITIAL | 0 | The ability is in the initial state.|
| FOCUS | 2 | The ability has the focus.| | FOCUS | 2 | The ability has the focus. |
| FOREGROUND | 9 | The ability is in the foreground state. | | FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. | | BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | | 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. | | BACKGROUNDING | 12 | The ability is in the state of being switched to the background. |
## updateConfiguration ## updateConfiguration
...@@ -39,7 +39,7 @@ Updates the configuration. This API uses an asynchronous callback to return the ...@@ -39,7 +39,7 @@ Updates the configuration. This API uses an asynchronous callback to return the
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -64,7 +64,7 @@ const config = { ...@@ -64,7 +64,7 @@ const config = {
language: 'Zh-Hans', // Simplified Chinese. language: 'Zh-Hans', // Simplified Chinese.
colorMode: COLOR_MODE_LIGHT, // Light theme. colorMode: COLOR_MODE_LIGHT, // Light theme.
direction: DIRECTION_VERTICAL, // Vertical direction. direction: DIRECTION_VERTICAL, // Vertical direction.
screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'.
displayId: 1, // The application is displayed on the display with ID 1. displayId: 1, // The application is displayed on the display with ID 1.
hasPointerDevice: true, // A pointer device is connected. hasPointerDevice: true, // A pointer device is connected.
}; };
...@@ -76,7 +76,7 @@ try { ...@@ -76,7 +76,7 @@ try {
} else { } else {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -122,7 +122,7 @@ const config = { ...@@ -122,7 +122,7 @@ const config = {
language: 'Zh-Hans', // Simplified Chinese. language: 'Zh-Hans', // Simplified Chinese.
colorMode: COLOR_MODE_LIGHT, // Light theme. colorMode: COLOR_MODE_LIGHT, // Light theme.
direction: DIRECTION_VERTICAL, // Vertical direction. direction: DIRECTION_VERTICAL, // Vertical direction.
screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'.
displayId: 1, // The application is displayed on the display with ID 1. displayId: 1, // The application is displayed on the display with ID 1.
hasPointerDevice: true, // A pointer device is connected. hasPointerDevice: true, // A pointer device is connected.
}; };
...@@ -132,7 +132,7 @@ try { ...@@ -132,7 +132,7 @@ try {
console.log('updateConfiguration success.'); console.log('updateConfiguration success.');
}).catch((err) => { }).catch((err) => {
console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); console.log('updateConfiguration fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -153,7 +153,7 @@ Obtains the UIAbility running information. This API uses an asynchronous callbac ...@@ -153,7 +153,7 @@ Obtains the UIAbility running information. This API uses an asynchronous callbac
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- | | --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | Yes | Callback used to return the API call result and the UIAbility running information. You can perform error handling or custom processing in this callback. | | callback | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | Yes | Callback used to return the API call result and the UIAbility running information. You can perform error handling or custom processing in this callback. |
**Error codes** **Error codes**
...@@ -274,7 +274,7 @@ try { ...@@ -274,7 +274,7 @@ try {
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>> getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the ExtensionAbility 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 **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -311,7 +311,7 @@ try { ...@@ -311,7 +311,7 @@ try {
console.log('getExtensionRunningInfos success, data: ' + JSON.stringify(data)); console.log('getExtensionRunningInfos success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getExtensionRunningInfos fail, err: ' + JSON.stringify(err)); console.log('getExtensionRunningInfos fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) console.log('error.code: ' + JSON.stringify(paramError.code)
+ ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message));
...@@ -359,7 +359,7 @@ abilityManager.getTopAbility((err, data) => { ...@@ -359,7 +359,7 @@ abilityManager.getTopAbility((err, data) => {
getTopAbility(): Promise\<ElementName>; getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value** **Return value**
...@@ -385,5 +385,5 @@ abilityManager.getTopAbility().then((data) => { ...@@ -385,5 +385,5 @@ abilityManager.getTopAbility().then((data) => {
console.log('getTopAbility success, data: ' + JSON.stringify(data)); console.log('getTopAbility success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getTopAbility fail, err: ' + JSON.stringify(err)); console.log('getTopAbility fail, err: ' + JSON.stringify(err));
}) });
``` ```
...@@ -45,7 +45,7 @@ appManager.isRunningInStabilityTest((err, flag) => { ...@@ -45,7 +45,7 @@ appManager.isRunningInStabilityTest((err, flag) => {
} else { } else {
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
} }
}) });
``` ```
...@@ -151,7 +151,7 @@ appManager.isRamConstrainedDevice((err, data) => { ...@@ -151,7 +151,7 @@ appManager.isRamConstrainedDevice((err, data) => {
} else { } else {
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.getAppMemorySize ## appManager.getAppMemorySize
...@@ -221,7 +221,7 @@ appManager.getAppMemorySize((err, data) => { ...@@ -221,7 +221,7 @@ appManager.getAppMemorySize((err, data) => {
} else { } else {
console.log('The size of app memory is:' + JSON.stringify(data)); console.log('The size of app memory is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.getRunningProcessInformation ## appManager.getRunningProcessInformation
...@@ -295,7 +295,7 @@ appManager.getRunningProcessInformation((err, data) => { ...@@ -295,7 +295,7 @@ appManager.getRunningProcessInformation((err, data) => {
} else { } else {
console.log('The process running information is:' + JSON.stringify(data)); console.log('The process running information is:' + JSON.stringify(data));
} }
}) });
``` ```
## appManager.on ## appManager.on
...@@ -352,7 +352,7 @@ let applicationStateObserver = { ...@@ -352,7 +352,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
try { try {
const observerId = appManager.on('applicationState', applicationStateObserver); const observerId = appManager.on('applicationState', applicationStateObserver);
console.log(`[appManager] observerCode: ${observerId}`); console.log(`[appManager] observerCode: ${observerId}`);
...@@ -416,7 +416,7 @@ let applicationStateObserver = { ...@@ -416,7 +416,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -478,7 +478,7 @@ let applicationStateObserver = { ...@@ -478,7 +478,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -559,7 +559,7 @@ let applicationStateObserver = { ...@@ -559,7 +559,7 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
} }
} };
let bundleNameList = ['bundleName1', 'bundleName2']; let bundleNameList = ['bundleName1', 'bundleName2'];
try { try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
...@@ -574,7 +574,7 @@ try { ...@@ -574,7 +574,7 @@ try {
console.log('unregisterApplicationStateObserver success, data: ' + JSON.stringify(data)); console.log('unregisterApplicationStateObserver success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('unregisterApplicationStateObserver faile, err: ' + JSON.stringify(err)); console.log('unregisterApplicationStateObserver faile, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -660,7 +660,7 @@ appManager.getForegroundApplications().then((data) => { ...@@ -660,7 +660,7 @@ appManager.getForegroundApplications().then((data) => {
console.log('getForegroundApplications success, data: ' + JSON.stringify(data)); console.log('getForegroundApplications success, data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getForegroundApplications fail, err: ' + JSON.stringify(err)); console.log('getForegroundApplications fail, err: ' + JSON.stringify(err));
}) });
``` ```
## appManager.killProcessWithAccount ## appManager.killProcessWithAccount
...@@ -702,7 +702,7 @@ try { ...@@ -702,7 +702,7 @@ try {
console.log('killProcessWithAccount success'); console.log('killProcessWithAccount success');
}).catch((err) => { }).catch((err) => {
console.error('killProcessWithAccount fail, err: ' + JSON.stringify(err)); console.error('killProcessWithAccount fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.error('error: ' + paramError.code + ', ' + paramError.message); console.error('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -844,7 +844,7 @@ try { ...@@ -844,7 +844,7 @@ try {
console.log('killProcessesByBundleName success.'); console.log('killProcessesByBundleName success.');
}).catch((err) => { }).catch((err) => {
console.log('killProcessesByBundleName fail, err: ' + JSON.stringify(err)); console.log('killProcessesByBundleName fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
...@@ -940,7 +940,7 @@ try { ...@@ -940,7 +940,7 @@ try {
console.log('clearUpApplicationData success.'); console.log('clearUpApplicationData success.');
}).catch((err) => { }).catch((err) => {
console.log('clearUpApplicationData fail, err: ' + JSON.stringify(err)); console.log('clearUpApplicationData fail, err: ' + JSON.stringify(err));
}) });
} catch (paramError) { } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
......
...@@ -21,8 +21,8 @@ Enumerates the application restart flags. This enum is used as an input paramete ...@@ -21,8 +21,8 @@ Enumerates the application restart flags. This enum is used as an input paramete
| Name | Value | Description | | Name | Value | Description |
| ---------- | ---- | ---------- | | ---------- | ---- | ---------- |
| ALWAYS_RESTART | 0 | The application is restarted in all cases.| | ALWAYS_RESTART | 0 | The application is restarted in all cases.|
| RESTART_WHEN_JS_CRASH | 0x0001 | The application is restarted in the case of JS_CRASH.| | RESTART_WHEN_JS_CRASH | 0x0001 | The application is restarted in the case of JS_CRASH. |
| RESTART_WHEN_APP_FREEZE | 0x0002 | The application is restarted in the case of APP_FREEZE.| | RESTART_WHEN_APP_FREEZE | 0x0002 | The application is restarted in the case of APP_FREEZE. |
| NO_RESTART | 0xFFFF | The application is not restarted in any case.| | NO_RESTART | 0xFFFF | The application is not restarted in any case.|
## appRecovery.SaveOccasionFlag ## appRecovery.SaveOccasionFlag
......
...@@ -10,7 +10,7 @@ The **Common** module provides all level-2 module APIs for developers to export. ...@@ -10,7 +10,7 @@ The **Common** module provides all level-2 module APIs for developers to export.
## Modules to Import ## Modules to Import
```ts ```ts
import common from '@ohos.app.ability.common' import common from '@ohos.app.ability.common';
``` ```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
...@@ -33,7 +33,7 @@ import common from '@ohos.app.ability.common' ...@@ -33,7 +33,7 @@ import common from '@ohos.app.ability.common'
**Example** **Example**
```ts ```ts
import common from '@ohos.app.ability.common' import common from '@ohos.app.ability.common';
let uiAbilityContext: common.UIAbilityContext; let uiAbilityContext: common.UIAbilityContext;
let abilityStageContext: common.AbilityStageContext; let abilityStageContext: common.AbilityStageContext;
......
# @ohos.app.ability.Configuration (Configuration) # @ohos.app.ability.Configuration (Configuration)
The **Configuration** module defines environment change information. The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import Configuration from '@ohos.app.ability.Configuration'
```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| language | string | Yes| Yes| Language of the application, for example, **zh**.| | 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**.| | colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode. The default value is **COLOR_MODE_LIGHT**. The options are as follows:<br>- **COLOR_MODE_NOT_SET**: The color mode is not set.<br>- **COLOR_MODE_LIGHT**: light mode.<br>- **COLOR_MODE_DARK**: dark mode.|
| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| | direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation. The options are as follows:<br>- **DIRECTION_NOT_SET**: The screen orientation is not set.<br>- **DIRECTION_HORIZONTAL**: horizontal direction.<br>- **DIRECTION_VERTICAL**: vertical direction.|
| 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).| | screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Pixel density of the screen. The options are as follows:<br>- **SCREEN_DENSITY_NOT_SET**: The pixel density is not set.<br>- **SCREEN_DENSITY_SDPI**: 120.<br>- **SCREEN_DENSITY_MDPI**: 160.<br>- **SCREEN_DENSITY_LDPI**: 240.<br>- **SCREEN_DENSITY_XLDPI**: 320.<br>- **SCREEN_DENSITY_XXLDPI**: 480.<br>- **SCREEN_DENSITY_XXXLDPI**: 640.|
| displayId | number | Yes| No| ID of the display where the application is located.| | 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.| | hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.|
...@@ -34,7 +28,7 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi ...@@ -34,7 +28,7 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi
onCreate(want, launchParam) { onCreate(want, launchParam) {
let envCallback = { let envCallback = {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`);
let language = config.language; let language = config.language;
let colorMode = config.colorMode; let colorMode = config.colorMode;
let direction = config.direction; let direction = config.direction;
...@@ -45,10 +39,10 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi ...@@ -45,10 +39,10 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi
}; };
try { try {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
let callbackId = applicationContext.on("environment", envCallback); let callbackId = applicationContext.on('environment', envCallback);
console.log("callbackId: " + callbackId); console.log('callbackId: ' + callbackId);
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
} }
} }
......
...@@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant ...@@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| COLOR_MODE_LIGHT | 1 | Light mode.| | COLOR_MODE_LIGHT | 1 | Light mode.|
## ConfigurationConstant.Direction ## ConfigurationConstant.Direction<sup>9+</sup>
You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. 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 ...@@ -38,7 +38,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| | DIRECTION_HORIZONTAL | 1 | Horizontal direction.|
## ConfigurationConstant.ScreenDensity ## ConfigurationConstant.ScreenDensity<sup>9+</sup>
You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API.
...@@ -46,10 +46,10 @@ You can obtain the value of this constant by calling the **ConfigurationConstant ...@@ -46,10 +46,10 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| Name| Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| | SCREEN_DENSITY_NOT_SET | 0 | The screen pixel density is not set.|
| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| | SCREEN_DENSITY_SDPI | 120 | The pixel density of the screen is 'sdpi'.|
| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| | SCREEN_DENSITY_MDPI | 160 | The pixel density of the screen is 'mdpi'.|
| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| | SCREEN_DENSITY_LDPI | 240 | The pixel density of the screen is 'ldpi'.|
| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| | SCREEN_DENSITY_XLDPI | 320 | The pixel density of the screen is 'xldpi'.|
| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| | SCREEN_DENSITY_XXLDPI | 480 | The pixel density of the screen is 'xxldpi'.|
| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| | SCREEN_DENSITY_XXXLDPI | 640 | The pixel density of the screen is 'xxxldpi'.|
...@@ -11,7 +11,7 @@ The **EnvironmentCallback** module provides the **onConfigurationUpdated** API f ...@@ -11,7 +11,7 @@ The **EnvironmentCallback** module provides the **onConfigurationUpdated** API f
## Modules to Import ## Modules to Import
```ts ```ts
import EnvironmentCallback from "@ohos.app.ability.EnvironmentCallback"; import EnvironmentCallback from '@ohos.app.ability.EnvironmentCallback';
``` ```
...@@ -29,33 +29,50 @@ Called when the system environment changes. ...@@ -29,33 +29,50 @@ Called when the system environment changes.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.| | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.|
## EnvironmentCallback.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system memory level changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**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.|
**Example** **Example**
```ts ```ts
import UIAbility from "@ohos.app.ability.Ability"; import Ability from '@ohos.application.Ability';
var callbackId; let callbackId;
export default class MyAbility extends UIAbility { export default class MyAbility extends Ability {
onCreate() { onCreate() {
console.log("MyAbility onCreate") console.log('MyAbility onCreate');
globalThis.applicationContext = this.context.getApplicationContext(); globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = { let EnvironmentCallback = {
onConfigurationUpdated(config){ onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config)); console.log('onConfigurationUpdated config:' + JSON.stringify(config));
},
onMemoryLevel(level){
console.log('onMemoryLevel level: ${JSON.stringify(level)}');
} }
} };
// 1. Obtain an applicationContext object. // 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
// 2. Register a listener for the environment changes through the applicationContext object. // 2. Register a listener for the environment changes through the applicationContext object.
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId));
} }
onDestroy() { onDestroy() {
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
}); });
} }
} }
......
# @ohos.app.ability.errorManager (ErrorManager) # @ohos.app.ability.errorManager (ErrorManager)
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. The **ErrorManager** module provides APIs for registering and deregistering error observers.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```ts ```
import errorManager from '@ohos.app.ability.errorManager' import errorManager from '@ohos.app.ability.errorManager'
``` ```
## ErrorManager.on ## ErrorManager.on
on(type: "error", observer: ErrorObserver): number; on(type: 'error', observer: ErrorObserver): number;
Registers an error observer. Registers an error observer.
...@@ -23,34 +23,27 @@ Registers an error observer. ...@@ -23,34 +23,27 @@ Registers an error observer.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| | type | string | Yes| Type of the API to call.|
| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.| | observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Index of the observer.|
**Example** **Example**
```ts ```js
var observer = { let observer = {
onUnhandledException(errorMsg) { onUnhandledException(errorMsg) {
console.log('onUnhandledException, errorMsg: ', errorMsg) console.log('onUnhandledException, errorMsg: ', errorMsg)
} }
} };
var observerId = -1;
try { try {
observerId = errorManager.on("error", observer); errorManager.on('error', observer);
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## ErrorManager.off ## ErrorManager.off
off(type: "error", observerId: number, callback: AsyncCallback\<void>): void; off(type: 'error', observerId: number, callback: AsyncCallback\<void>): void;
Deregisters an error observer. This API uses an asynchronous callback to return the result. Deregisters an error observer. This API uses an asynchronous callback to return the result.
...@@ -60,14 +53,14 @@ Deregisters an error observer. This API uses an asynchronous callback to return ...@@ -60,14 +53,14 @@ Deregisters an error observer. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| | type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Index of the observer returned by **on()**.| | observerId | number | Yes| Digital code of the observer.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
```ts ```js
var observerId = 100; let observerId = 100;
function unregisterErrorObserverCallback(err) { function unregisterErrorObserverCallback(err) {
if (err) { if (err) {
...@@ -75,15 +68,15 @@ function unregisterErrorObserverCallback(err) { ...@@ -75,15 +68,15 @@ function unregisterErrorObserverCallback(err) {
} }
} }
try { try {
errorManager.off("error", observerId, unregisterErrorObserverCallback); errorManager.off('error', observerId, unregisterErrorObserverCallback);
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## ErrorManager.off ## ErrorManager.off
off(type: "error", observerId: number): Promise\<void>; off(type: 'error', observerId: number): Promise\<void>;
Deregisters an error observer. This API uses a promise to return the result. Deregisters an error observer. This API uses a promise to return the result.
...@@ -93,8 +86,8 @@ Deregisters an error observer. This API uses a promise to return the result. ...@@ -93,8 +86,8 @@ Deregisters an error observer. This API uses a promise to return the result.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| | type | string | Yes| Type of the API to call.|
| observerId | number | Yes| Index of the observer returned by **on()**.| | observerId | number | Yes| Digital code of the observer.|
**Return value** **Return value**
...@@ -104,18 +97,18 @@ Deregisters an error observer. This API uses a promise to return the result. ...@@ -104,18 +97,18 @@ Deregisters an error observer. This API uses a promise to return the result.
**Example** **Example**
```ts ```js
var observerId = 100; let observerId = 100;
try { try {
errorManager.off("error", observerId) errorManager.off('error', observerId)
.then((data) => { .then((data) => {
console.log('----------- unregisterErrorObserver success ----------', data); console.log('----------- unregisterErrorObserver success ----------', data);
}) })
.catch((err) => { .catch((err) => {
console.log('----------- unregisterErrorObserver fail ----------', err); console.log('----------- unregisterErrorObserver fail ----------', err);
}) });
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -18,7 +18,7 @@ ohos.permission.MANAGE_MISSIONS ...@@ -18,7 +18,7 @@ ohos.permission.MANAGE_MISSIONS
## missionManager.on ## missionManager.on
on(type:"mission", listener: MissionListener): number; on(type:'mission', listener: MissionListener): number;
Registers a listener to observe the mission status. Registers a listener to observe the mission status.
...@@ -43,69 +43,26 @@ Registers a listener to observe the mission status. ...@@ -43,69 +43,26 @@ Registers a listener to observe the mission status.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; let listener = {
import UIAbility from '@ohos.app.ability.UIAbility'; onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
var listener = { onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, };
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, console.log('registerMissionListener');
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, try {
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} let listenerid = missionManager.on('mission', listener);
}; } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
var listenerId = -1; }
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate");
globalThis.abilityWant = want;
globalThis.context = this.context;
}
onDestroy() {
try {
if (listenerId != -1) {
missionManager.off("mission", listenerId).catch(function (err) {
console.log(err);
});
}
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
windowStage.loadContent("pages/index", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
});
if (globalThis.flag) {
return;
}
}
};
``` ```
## missionManager.off ## missionManager.off
off(type: "mission", listenerId: number, callback: AsyncCallback&lt;void&gt;): void; off(type: 'mission', listenerId: number, callback: AsyncCallback&lt;void&gt;): void;
Deregisters a mission status listener. Deregisters a mission status listener.
...@@ -119,75 +76,36 @@ Deregisters a mission status listener. ...@@ -119,75 +76,36 @@ Deregisters a mission status listener.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| | 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.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; let listener = {
import UIAbility from '@ohos.app.ability.UIAbility'; onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
var listener = { onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, };
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, console.log('registerMissionListener');
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, try {
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} let listenerid = missionManager.registerMissionListener(listener);
};
missionManager.unregisterMissionListener(listenerid, (error) => {
var listenerId = -1; console.log('unregisterMissionListener');
});
export default class EntryAbility extends UIAbility { } catch (paramError) {
onCreate(want, launchParam) { console.log('error: ' + paramError.code + ', ' + paramError.message);
console.log("[Demo] EntryAbility onCreate") }
globalThis.abilityWant = want;
globalThis.context = this.context;
}
onDestroy() {
try {
if (listenerId != -1) {
missionManager.off("mission", listenerId, (err) => {
console.log(err);
});
}
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
windowStage.loadContent("pages/index", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
});
if (globalThis.flag) {
return;
}
}
};
``` ```
## missionManager.off ## missionManager.off
off(type: "mission", listenerId: number): Promise&lt;void&gt;; off(type: 'mission', listenerId: number): Promise&lt;void&gt;;
Deregisters a mission status listener. This API uses a promise to return the result. Deregisters a mission status listener. This API uses a promise to return the result.
...@@ -201,7 +119,7 @@ Deregisters a mission status listener. This API uses a promise to return the res ...@@ -201,7 +119,7 @@ Deregisters a mission status listener. This API uses a promise to return the res
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.|
**Return value** **Return value**
...@@ -212,63 +130,24 @@ Deregisters a mission status listener. This API uses a promise to return the res ...@@ -212,63 +130,24 @@ Deregisters a mission status listener. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; let listener = {
import UIAbility from '@ohos.app.ability.UIAbility'; onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
var listener = { onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, };
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, console.log('registerMissionListener');
onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, try {
onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} let listenerid = missionManager.registerMissionListener(listener);
};
missionManager.unregisterMissionListener(listenerid).catch(function (err) {
var listenerId = -1; console.log(err);
});
export default class EntryAbility extends UIAbility { } catch (paramError) {
onCreate(want, launchParam) { console.log('error: ' + paramError.code + ', ' + paramError.message);
console.log("[Demo] EntryAbility onCreate") }
globalThis.abilityWant = want;
globalThis.context = this.context;
}
onDestroy() {
try {
if (listenerId != -1) {
missionManager.off("mission", listenerId).catch(function (err) {
console.log(err);
});
}
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
console.log("[Demo] EntryAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// The main window is created. Set a main page for this ability.
console.log("[Demo] EntryAbility onWindowStageCreate")
try {
listenerId = missionManager.on("mission", listener);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
windowStage.loadContent("pages/index", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
});
if (globalThis.flag) {
return;
}
}
};
``` ```
...@@ -297,28 +176,19 @@ Obtains the information about a given mission. This API uses an asynchronous cal ...@@ -297,28 +176,19 @@ Obtains the information about a given mission. This API uses an asynchronous cal
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 1;
try { try {
var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);});
if (allMissions && allMissions.length > 0) { missionManager.getMissionInfo('', allMissions[0].missionId, (error, mission) => {
testMissionId = allMissions[0].missionId; console.log('getMissionInfo is called, error.code = ' + error.code);
} console.log('mission.missionId = ' + mission.missionId);
console.log('mission.runningState = ' + mission.runningState);
missionManager.getMissionInfo("", testMissionId, (error, mission) => { console.log('mission.lockedState = ' + mission.lockedState);
if (error) { console.log('mission.timestamp = ' + mission.timestamp);
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + console.log('mission.label = ' + mission.label);
"error.message:" + JSON.stringify(error.message)); console.log('mission.iconPath = ' + mission.iconPath);
} 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) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -350,20 +220,18 @@ Obtains the information about a given mission. This API uses a promise to return ...@@ -350,20 +220,18 @@ Obtains the information about a given mission. This API uses a promise to return
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 1; try {
try { let mission = missionManager.getMissionInfo('', 10).catch(function (err){
missionManager.getMissionInfo("", testMissionId).then((data) => { console.log(err);
console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data));
}).catch(error => {
console.error('getMissionInfo failed. Cause: ' + error.message);
}); });
} catch (error) { } catch (paramError) {
console.error('getMissionInfo failed. Cause: ' + error.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.getMissionInfos ## missionManager.getMissionInfos
...@@ -391,17 +259,13 @@ Obtains information about all missions. This API uses an asynchronous callback t ...@@ -391,17 +259,13 @@ Obtains information about all missions. This API uses an asynchronous callback t
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
try { try {
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
} else { });
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
}
})
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -433,19 +297,18 @@ Obtains information about all missions. This API uses a promise to return the re ...@@ -433,19 +297,18 @@ Obtains information about all missions. This API uses a promise to return the re
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
try { try {
missionManager.getMissionInfos("", 10).then((data) => { let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){
console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); console.log(err);
}).catch(error => {
console.error('getMissionInfos failed. Cause: ' + error.message);
}); });
} catch (error) { } catch (paramError) {
console.error('getMissionInfos failed. Cause: ' + error.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.getMissionSnapShot ## missionManager.getMissionSnapShot
...@@ -468,22 +331,27 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback ...@@ -468,22 +331,27 @@ 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.| | callback | AsyncCallback&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Yes| Callback used to return the snapshot information obtained.|
**Example** **Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; ```ts
try { import missionManager from '@ohos.app.ability.missionManager';
missionManager.getMissionSnapShot("", testMissionId, (err, data) => {
if (err) { try {
console.error('getMissionSnapShot failed:' + err.message); missionManager.getMissionInfos('', 10, (error, missions) => {
} else { console.log('getMissionInfos is called, error.code = ' + error.code);
console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); console.log('size = ' + missions.length);
} console.log('missions = ' + JSON.stringify(missions));
let 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 (err) { } catch (paramError) {
console.error('getMissionSnapShot failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.getMissionSnapShot ## missionManager.getMissionSnapShot
...@@ -511,20 +379,26 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r ...@@ -511,20 +379,26 @@ 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.| | Promise&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Promise used to return the snapshot information obtained.|
**Example** **Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; ```ts
try { import missionManager from '@ohos.app.ability.missionManager';
missionManager.getMissionSnapShot("", testMissionId).then((data) => {
console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); try {
}).catch(error => { let allMissions;
console.error('getMissionSnapShot failed. Cause: ' + error.message); missionManager.getMissionInfos('',10).then(function(res){
}); allMissions=res;
} catch (error) { }).catch(function(err){console.log(err);});
console.error('getMissionSnapShot failed. Cause: ' + error.message); console.log('size = ' + allMissions.length);
} console.log('missions = ' + JSON.stringify(allMissions));
``` let id = allMissions[0].missionId;
let snapshot = missionManager.getMissionSnapShot('', id).catch(function (err){
console.log(err);
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
## missionManager.getLowResolutionMissionSnapShot ## missionManager.getLowResolutionMissionSnapShot
...@@ -547,22 +421,27 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr ...@@ -547,22 +421,27 @@ 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.| | callback | AsyncCallback&lt;[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)&gt; | Yes| Callback used to return the snapshot information obtained.|
**Example** **Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; ```ts
try { import missionManager from '@ohos.app.ability.missionManager';
missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => {
if (err) { try {
console.error('getLowResolutionMissionSnapShot failed:' + err.message); missionManager.getMissionInfos('', 10, (error, missions) => {
} else { console.log('getMissionInfos is called, error.code = ' + error.code);
console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); console.log('size = ' + missions.length);
} console.log('missions = ' + JSON.stringify(missions));
let 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 (err) { } catch (paramError) {
console.error('getLowResolutionMissionSnapShot failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.getLowResolutionMissionSnapShot ## missionManager.getLowResolutionMissionSnapShot
...@@ -591,20 +470,25 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise ...@@ -591,20 +470,25 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { let allMissions;
missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { missionManager.getMissionInfos('',10).then(function(res){
console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); allMissions=res;
}).catch(error => { }).catch(function(err){console.log(err);});
console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); console.log('size = ' + allMissions.length);
}); console.log('missions = ' + JSON.stringify(allMissions));
} catch (error) { let id = allMissions[0].missionId;
console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message);
} let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (err){
``` console.log(err);
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
## missionManager.lockMission ## missionManager.lockMission
...@@ -628,22 +512,25 @@ Locks a given mission. This API uses an asynchronous callback to return the resu ...@@ -628,22 +512,25 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { missionManager.getMissionInfos('', 10, (error, missions) => {
missionManager.lockMission(testMissionId, (err, data) => { console.log('getMissionInfos is called, error.code = ' + error.code);
if (err) { console.log('size = ' + missions.length);
console.error('lockMission failed:' + err.message); console.log('missions = ' + JSON.stringify(missions));
} else { let id = missions[0].missionId;
console.info('lockMission successfully:' + JSON.stringify(data));
} missionManager.lockMission(id).then(() => {
console.log('lockMission is called ');
});
}); });
} catch (err) { } catch (paramError) {
console.error('lockMission failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.lockMission ## missionManager.lockMission
...@@ -670,20 +557,27 @@ Locks a given mission. This API uses a promise to return the result. ...@@ -670,20 +557,27 @@ Locks a given mission. This API uses a promise to return the result.
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; ```ts
try { import missionManager from '@ohos.app.ability.missionManager';
missionManager.lockMission(testMissionId).then((data) => {
console.info('lockMission successfully. Data: ' + JSON.stringify(data)); try {
}).catch(error => { let allMissions;
console.error('lockMission failed. Cause: ' + error.message); 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));
let id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){
console.log(err);
}); });
} catch (error) { } catch (paramError) {
console.error('lockMission failed. Cause: ' + error.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.unlockMission ## missionManager.unlockMission
...@@ -705,22 +599,26 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re ...@@ -705,22 +599,26 @@ 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.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; ```ts
try { import missionManager from '@ohos.app.ability.missionManager';
missionManager.unlockMission(testMissionId, (err, data) => {
if (err) { try {
console.error('unlockMission failed:' + err.message); missionManager.getMissionInfos('', 10, (error, missions) => {
} else { console.log('getMissionInfos is called, error.code = ' + error.code);
console.info('unlockMission successfully:' + JSON.stringify(data)); console.log('size = ' + missions.length);
} console.log('missions = ' + JSON.stringify(missions));
let id = missions[0].missionId;
missionManager.unlockMission(id).then(() => {
console.log('unlockMission is called ');
});
}); });
} catch (err) { } catch (paramError) {
console.error('unlockMission failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.unlockMission ## missionManager.unlockMission
...@@ -748,20 +646,29 @@ Unlocks a given mission. This API uses a promise to return the result. ...@@ -748,20 +646,29 @@ Unlocks a given mission. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { let allMissions;
missionManager.unlockMission(testMissionId).then((data) => { missionManager.getMissionInfos('',10).then(function(res){
console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); allMissions=res;
}).catch(error => { }).catch(function(err){console.log(err);});
console.error('unlockMission failed. Cause: ' + error.message); console.log('size = ' + allMissions.length);
console.log('missions = ' + JSON.stringify(allMissions));
let id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){
console.log(err);
}); });
} catch (error) { missionManager.unlockMission(id).catch(function (err){
console.error('unlockMission failed. Cause: ' + error.message); console.log(err);
} });
``` } catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
## missionManager.clearMission ## missionManager.clearMission
...@@ -784,22 +691,24 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy ...@@ -784,22 +691,24 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { missionManager.getMissionInfos('', 10, (error, missions) => {
missionManager.clearMission(testMissionId, (err, data) => { console.log('getMissionInfos is called, error.code = ' + error.code);
if (err) { console.log('size = ' + missions.length);
console.error('clearMission failed:' + err.message); console.log('missions = ' + JSON.stringify(missions));
} else { let id = missions[0].missionId;
console.info('clearMission successfully:' + JSON.stringify(data));
} missionManager.clearMission(id).then(() => {
console.log('clearMission is called ');
});
}); });
} catch (err) { } catch (paramError) {
console.error('clearMission failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.clearMission ## missionManager.clearMission
...@@ -828,20 +737,26 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom ...@@ -828,20 +737,26 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { let allMissions;
missionManager.clearMission(testMissionId).then((data) => { missionManager.getMissionInfos('',10).then(function(res){
console.info('clearMission successfully. Data: ' + JSON.stringify(data)); allMissions=res;
}).catch(error => { }).catch(function(err){console.log(err);});
console.error('clearMission failed. Cause: ' + error.message); console.log('size = ' + allMissions.length);
console.log('missions = ' + JSON.stringify(allMissions));
let id = allMissions[0].missionId;
missionManager.clearMission(id).catch(function (err){
console.log(err);
}); });
} catch (error) { } catch (paramError) {
console.error('clearMission failed. Cause: ' + error.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.clearAllMissions ## missionManager.clearAllMissions
...@@ -857,21 +772,14 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t ...@@ -857,21 +772,14 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; 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 ## missionManager.clearAllMissions
...@@ -893,19 +801,13 @@ Clears all unlocked missions. This API uses a promise to return the result. ...@@ -893,19 +801,13 @@ Clears all unlocked missions. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
missionManager.clearAllMissions().catch(function (err){
console.log(err);
});
```
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 ## missionManager.moveMissionToFront
...@@ -928,22 +830,25 @@ Switches a given mission to the foreground. This API uses an asynchronous callba ...@@ -928,22 +830,25 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { missionManager.getMissionInfos('', 10, (error, missions) => {
missionManager.moveMissionToFront(testMissionId, (err, data) => { console.log('getMissionInfos is called, error.code = ' + error.code);
if (err) { console.log('size = ' + missions.length);
console.error('moveMissionToFront failed:' + err.message); console.log('missions = ' + JSON.stringify(missions));
} else { let id = missions[0].missionId;
console.info('moveMissionToFront successfully:' + JSON.stringify(data));
} missionManager.moveMissionToFront(id).then(() => {
console.log('moveMissionToFront is called ');
});
}); });
} catch (err) { } catch (paramError) {
console.error('moveMissionToFront failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.moveMissionToFront ## missionManager.moveMissionToFront
...@@ -967,22 +872,25 @@ Switches a given mission to the foreground, with the startup parameters for the ...@@ -967,22 +872,25 @@ Switches a given mission to the foreground, with the startup parameters for the
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { missionManager.getMissionInfos('', 10, (error, missions) => {
missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { console.log('getMissionInfos is called, error.code = ' + error.code);
if (err) { console.log('size = ' + missions.length);
console.error('moveMissionToFront failed:' + err.message); console.log('missions = ' + JSON.stringify(missions));
} else { let id = missions[0].missionId;
console.info('moveMissionToFront successfully:' + JSON.stringify(data));
} missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => {
console.log('moveMissionToFront is called ');
});
}); });
} catch (err) { } catch (paramError) {
console.error('moveMissionToFront failed:' + err.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## missionManager.moveMissionToFront ## missionManager.moveMissionToFront
...@@ -1011,17 +919,22 @@ Switches a given mission to the foreground, with the startup parameters for the ...@@ -1011,17 +919,22 @@ Switches a given mission to the foreground, with the startup parameters for the
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.app.ability.missionManager';
let testMissionId = 2; try {
try { let allMissions;
missionManager.moveMissionToFront(testMissionId).then((data) => { missionManager.getMissionInfos('',10).then(function(res){
console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); allMissions=res;
}).catch(error => { }).catch(function(err){console.log(err);});
console.error('moveMissionToFront failed. Cause: ' + error.message); console.log('size = ' + allMissions.length);
console.log('missions = ' + JSON.stringify(allMissions));
let id = allMissions[0].missionId;
missionManager.moveMissionToFront(id).catch(function (err){
console.log(err);
}); });
} catch (error) { } catch (paramError) {
console.error('moveMissionToFront failed. Cause: ' + error.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
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. 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.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -24,7 +24,7 @@ Defines the quick fix information at the HAP file level. ...@@ -24,7 +24,7 @@ Defines the quick fix information at the HAP file level.
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| moduleName | string | Yes | Name of the HAP file. | | moduleName | string | Yes | Name of the HAP file. |
| originHapHash | string | Yes | Hash value of the HAP file. | | originHapHash | string | Yes | Hash value of the HAP file. |
| quickFixFilePath | string | Yes | Installation path of the quick fix file. | | quickFixFilePath | string | Yes | Installation path of the quick fix patch file. |
## ApplicationQuickFixInfo ## ApplicationQuickFixInfo
...@@ -57,25 +57,31 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the ...@@ -57,25 +57,31 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Parameter| Type| Mandatory| Description| | Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix files, each of which must contain a valid file path.| | hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
> **NOTE**
>
> The file path passed in the API must be an application sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](js-apis-bundle-BundleInstaller.md#obtaining-the-sandbox-path). The path mapped to the device is **/proc/<*applicationProcessId*>/root/*sandboxPath***.
**Example** **Example**
```ts ```ts
import quickFixManager from '@ohos.app.ability.quickFixManager';
try { try {
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf'];
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
if (error) { if (error) {
console.info( `applyQuickFix failed with error + ${error}`) console.info( `applyQuickFix failed with error + ${error}`);
} else { } else {
console.info( 'applyQuickFix success') console.info( 'applyQuickFix success');
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -93,28 +99,30 @@ Applies a quick fix patch. This API uses a promise to return the result. ...@@ -93,28 +99,30 @@ Applies a quick fix patch. This API uses a promise to return the result.
**Parameters** **Parameters**
| Parameter| Type| Mandatory| Description| | Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix files, each of which must contain a valid file path.| | hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
```ts ```ts
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] import quickFixManager from '@ohos.app.ability.quickFixManager';
let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf'];
try { try {
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
console.info('applyQuickFix success') console.info('applyQuickFix success');
}).catch((error) => { }).catch((error) => {
console.info(`applyQuickFix err: + ${error}`) console.info(`applyQuickFix err: + ${error}`);
}) });
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -138,20 +146,22 @@ Obtains the quick fix information of the application. This API uses an asynchron ...@@ -138,20 +146,22 @@ Obtains the quick fix information of the application. This API uses an asynchron
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
**Example** **Example**
```ts ```ts
import quickFixManager from '@ohos.app.ability.quickFixManager';
try { try {
let bundleName = "bundleName" let bundleName = 'bundleName'
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
if (error) { if (error) {
console.info(`getApplicationQuickFixInfo error: + ${error}`) console.info(`getApplicationQuickFixInfo error: + ${error}`);
} else { } else {
console.info(`getApplicationQuickFixInfo success: + ${data}`) console.info(`getApplicationQuickFixInfo success: + ${data}`);
} }
}) });
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## quickFixManager.getApplicationQuickFixInfo ## quickFixManager.getApplicationQuickFixInfo
...@@ -174,21 +184,23 @@ Obtains the quick fix information of the application. This API uses a promise to ...@@ -174,21 +184,23 @@ Obtains the quick fix information of the application. This API uses a promise to
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Example** **Example**
```ts ```ts
import quickFixManager from '@ohos.app.ability.quickFixManager';
try { try {
let bundleName = "bundleName" let bundleName = 'bundleName';
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
console.info(`getApplicationQuickFixInfo success: + ${data}`) console.info(`getApplicationQuickFixInfo success: + ${data}`);
}).catch((error) => { }).catch((error) => {
console.info(`getApplicationQuickFixInfo err: + ${error}`) console.info(`getApplicationQuickFixInfo err: + ${error}`);
}) });
} catch (paramError) { } catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
# @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility) # @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)
The **ServiceExtensionAbility** module provides lifecycle callbacks when a ServiceExtensionAbility (background service) is created, destroyed, connected, or disconnected. The **ServiceExtensionAbility** module provides APIs for ServiceExtensionAbilities.
> **NOTE** > **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. > The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
...@@ -80,7 +80,7 @@ Called when this ServiceExtensionAbility is destroyed to clear resources. ...@@ -80,7 +80,7 @@ Called when this ServiceExtensionAbility is destroyed to clear resources.
onRequest(want: Want, startId: number): void; onRequest(want: Want, startId: number): void;
Called following **onCreate()** when a ServiceExtensionAbility 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()** or **startServiceExtensionAbility()**. The value of **startId** is incremented for each ability that is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -129,7 +129,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ...@@ -129,7 +129,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal
**Example** **Example**
```ts ```ts
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject{ class StubTest extends rpc.RemoteObject{
constructor(des) { constructor(des) {
super(des); super(des);
...@@ -140,7 +140,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ...@@ -140,7 +140,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal
class ServiceExt extends ServiceExtension { class ServiceExt extends ServiceExtension {
onConnect(want) { onConnect(want) {
console.log('onConnect , want:' + want.abilityName); console.log('onConnect , want:' + want.abilityName);
return new StubTest("test"); return new StubTest('test');
} }
} }
``` ```
...@@ -150,7 +150,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ...@@ -150,7 +150,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal
onDisconnect(want: Want): void; onDisconnect(want: Want): void;
Called when a client is disconnected from this ServiceExtensionAbility. Called when this ServiceExtensionAbility is disconnected.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -176,7 +176,7 @@ Called when a client is disconnected from this ServiceExtensionAbility. ...@@ -176,7 +176,7 @@ Called when a client is disconnected from this ServiceExtensionAbility.
onReconnect(want: Want): void; onReconnect(want: Want): void;
Called when a new client attempts to connect to this ServiceExtensionAbility after all previous clients are disconnected. This capability is reserved. Called when this ServiceExtensionAbility is reconnected.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -246,7 +246,8 @@ Dumps the client information. ...@@ -246,7 +246,8 @@ Dumps the client information.
class ServiceExt extends ServiceExtension { class ServiceExt extends ServiceExtension {
onDump(params) { onDump(params) {
console.log('dump, params:' + JSON.stringify(params)); console.log('dump, params:' + JSON.stringify(params));
return ["params"] return ['params'];
} }
} }
``` ```
# @ohos.app.ability.UIAbility (UIAbility) # @ohos.app.ability.UIAbility (UIAbility)
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: The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
- [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). This module provides the following common ability-related functions:
- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). - [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.
> **NOTE** > **NOTE**
> >
...@@ -13,7 +14,7 @@ UIAbility is an application component that has the UI. The **UIAbility** module ...@@ -13,7 +14,7 @@ UIAbility is an application component that has the UI. The **UIAbility** module
## Modules to Import ## Modules to Import
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.app.ability.UIAbility';
``` ```
## Attributes ## Attributes
...@@ -22,16 +23,16 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -22,16 +23,16 @@ import UIAbility from '@ohos.app.ability.UIAbility';
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| | context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the ability.|
| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| | 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 UIAbility was started last time.| | lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| | callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
## UIAbility.onCreate ## Ability.onCreate
onCreate(want: Want, param: AbilityConstant.LaunchParam): void; onCreate(want: Want, param: AbilityConstant.LaunchParam): void;
Called to initialize the service logic when a UIAbility is created. Called to initialize the service logic when an ability is created.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -39,13 +40,13 @@ Called to initialize the service logic when a UIAbility is created. ...@@ -39,13 +40,13 @@ Called to initialize the service logic when a UIAbility is created.
| Name| Type| Mandatory| Description| | 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.| | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, 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.| | param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.|
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onCreate(want, param) { onCreate(want, param) {
console.log('onCreate, want:' + want.abilityName); console.log('onCreate, want:' + want.abilityName);
} }
...@@ -53,11 +54,11 @@ Called to initialize the service logic when a UIAbility is created. ...@@ -53,11 +54,11 @@ Called to initialize the service logic when a UIAbility is created.
``` ```
## UIAbility.onWindowStageCreate ## Ability.onWindowStageCreate
onWindowStageCreate(windowStage: window.WindowStage): void onWindowStageCreate(windowStage: window.WindowStage): void
Called when a **WindowStage** is created for this UIAbility. Called when a **WindowStage** is created for this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -70,7 +71,7 @@ Called when a **WindowStage** is created for this UIAbility. ...@@ -70,7 +71,7 @@ Called when a **WindowStage** is created for this UIAbility.
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
} }
...@@ -78,18 +79,18 @@ Called when a **WindowStage** is created for this UIAbility. ...@@ -78,18 +79,18 @@ Called when a **WindowStage** is created for this UIAbility.
``` ```
## UIAbility.onWindowStageDestroy ## Ability.onWindowStageDestroy
onWindowStageDestroy(): void onWindowStageDestroy(): void
Called when the **WindowStage** is destroyed for this UIAbility. Called when the **WindowStage** is destroyed for this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
console.log('onWindowStageDestroy'); console.log('onWindowStageDestroy');
} }
...@@ -97,11 +98,11 @@ Called when the **WindowStage** is destroyed for this UIAbility. ...@@ -97,11 +98,11 @@ Called when the **WindowStage** is destroyed for this UIAbility.
``` ```
## UIAbility.onWindowStageRestore ## Ability.onWindowStageRestore
onWindowStageRestore(windowStage: window.WindowStage): void onWindowStageRestore(windowStage: window.WindowStage): void
Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -114,7 +115,7 @@ Called when the **WindowStage** is restored during the migration of this UIAbili ...@@ -114,7 +115,7 @@ Called when the **WindowStage** is restored during the migration of this UIAbili
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onWindowStageRestore(windowStage) { onWindowStageRestore(windowStage) {
console.log('onWindowStageRestore'); console.log('onWindowStageRestore');
} }
...@@ -122,18 +123,18 @@ Called when the **WindowStage** is restored during the migration of this UIAbili ...@@ -122,18 +123,18 @@ Called when the **WindowStage** is restored during the migration of this UIAbili
``` ```
## UIAbility.onDestroy ## Ability.onDestroy
onDestroy(): void; onDestroy(): void;
Called when this UIAbility is destroyed to clear resources. Called when this ability is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onDestroy() { onDestroy() {
console.log('onDestroy'); console.log('onDestroy');
} }
...@@ -141,18 +142,18 @@ Called when this UIAbility is destroyed to clear resources. ...@@ -141,18 +142,18 @@ Called when this UIAbility is destroyed to clear resources.
``` ```
## UIAbility.onForeground ## Ability.onForeground
onForeground(): void; onForeground(): void;
Called when this UIAbility is switched from the background to the foreground. Called when this ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onForeground() { onForeground() {
console.log('onForeground'); console.log('onForeground');
} }
...@@ -160,18 +161,18 @@ Called when this UIAbility is switched from the background to the foreground. ...@@ -160,18 +161,18 @@ Called when this UIAbility is switched from the background to the foreground.
``` ```
## UIAbility.onBackground ## Ability.onBackground
onBackground(): void; onBackground(): void;
Called when this UIAbility is switched from the foreground to the background. Called when this ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onBackground() { onBackground() {
console.log('onBackground'); console.log('onBackground');
} }
...@@ -179,7 +180,7 @@ Called when this UIAbility is switched from the foreground to the background. ...@@ -179,7 +180,7 @@ Called when this UIAbility is switched from the foreground to the background.
``` ```
## UIAbility.onContinue ## Ability.onContinue
onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;
...@@ -202,22 +203,22 @@ Called to save data during the ability migration preparation process. ...@@ -202,22 +203,22 @@ Called to save data during the ability migration preparation process.
**Example** **Example**
```ts ```ts
import AbilityConstant from "@ohos.app.ability.AbilityConstant" import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onContinue(wantParams) { onContinue(wantParams) {
console.log('onContinue'); console.log('onContinue');
wantParams["myData"] = "my1234567"; wantParams['myData'] = 'my1234567';
return AbilityConstant.OnContinueResult.AGREE; return AbilityConstant.OnContinueResult.AGREE;
} }
} }
``` ```
## UIAbility.onNewWant ## Ability.onNewWant
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;
Called when a new Want is passed in and this UIAbility is started again. Called when a new Want is passed in and this ability is started again.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -226,20 +227,20 @@ Called when a new Want is passed in and this UIAbility is started again. ...@@ -226,20 +227,20 @@ Called when a new Want is passed in and this UIAbility is started again.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| | 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.| | launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the ability startup and the last abnormal exit.|
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onNewWant(want, launchParams) { onNewWant(want, launchParams) {
console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, want:' + want.abilityName);
console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); console.log('onNewWant, launchParams:' + JSON.stringify(launchParams));
} }
} }
``` ```
## UIAbility.onDump ## Ability.onDump
onDump(params: Array\<string>): Array\<string>; onDump(params: Array\<string>): Array\<string>;
...@@ -256,20 +257,20 @@ Dumps client information. ...@@ -256,20 +257,20 @@ Dumps client information.
**Example** **Example**
```ts ```ts
class MyUIAbility extends UIAbility { class myAbility extends Ability {
onDump(params) { onDump(params) {
console.log('dump, params:' + JSON.stringify(params)); console.log('dump, params:' + JSON.stringify(params));
return ["params"] return ['params'];
} }
} }
``` ```
## UIAbility.onSaveState ## Ability.onSaveState
onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;
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. 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). If automatic state saving is enabled, **onSaveState** is called to save the state of this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -277,24 +278,24 @@ Called when the framework automatically saves the UIAbility state in the case of ...@@ -277,24 +278,24 @@ Called when the framework automatically saves the UIAbility state in the case of
| Name| Type| Mandatory| Description| | 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.| | 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.| | wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| | AbilityConstant.OnSaveResult | Whether the ability state is saved.|
**Example** **Example**
```ts ```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant' import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onSaveState(reason, wantParam) { onSaveState(reason, wantParam) {
console.log('onSaveState'); console.log('onSaveState');
wantParam["myData"] = "my1234567"; wantParam['myData'] = 'my1234567';
return AbilityConstant.OnSaveResult.RECOVERY_AGREE; return AbilityConstant.OnSaveResult.RECOVERY_AGREE;
} }
} }
...@@ -338,9 +339,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -338,9 +339,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
class MyMessageAble{ // Custom sequenceable data structure. import Ability from '@ohos.app.ability.UIAbility';
name:"" class MyMessageAble{ // ԶSequenceableݽṹ
str:"" name:''
str:''
num: 1 num: 1
constructor(name, str) { constructor(name, str) {
this.name = name; this.name = name;
...@@ -359,17 +361,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -359,17 +361,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
return true; return true;
} }
}; };
var method = 'call_Function'; // Notification message string negotiated by the two abilities. let method = 'call_Function'; // Notification message string negotiated by the two abilities.
var caller; let caller;
export default class MainUIAbility extends UIAbility { export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.context.startUIAbilityByCall({ this.context.startAbilityByCall({
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
abilityName: "MainUIAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
let msg = new MyMessageAble("msg", "world"); // See the definition of Sequenceable. let msg = new MyMessageAble('msg', 'world'); // See the definition of Sequenceable.
caller.call(method, msg) caller.call(method, msg)
.then(() => { .then(() => {
console.log('Caller call() called'); console.log('Caller call() called');
...@@ -419,9 +422,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -419,9 +422,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{ class MyMessageAble{
name:"" name:''
str:"" str:''
num: 1 num: 1
constructor(name, str) { constructor(name, str) {
this.name = name; this.name = name;
...@@ -440,21 +444,21 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -440,21 +444,21 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
return true; return true;
} }
}; };
var method = 'call_Function'; let method = 'call_Function';
var caller; let caller;
export default class MainUIAbility extends UIAbility { export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.context.startUIAbilityByCall({ this.context.startAbilityByCall({
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
abilityName: "MainUIAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
let msg = new MyMessageAble(1, "world"); let msg = new MyMessageAble(1, 'world');
caller.callWithResult(method, msg) caller.callWithResult(method, msg)
.then((data) => { .then((data) => {
console.log('Caller callWithResult() called'); console.log('Caller callWithResult() called');
let retmsg = new MyMessageAble(0, ""); let retmsg = new MyMessageAble(0, '');
data.readSequenceable(retmsg); data.readSequenceable(retmsg);
}) })
.catch((callErr) => { .catch((callErr) => {
...@@ -490,13 +494,14 @@ Releases the caller interface of the target ability. ...@@ -490,13 +494,14 @@ Releases the caller interface of the target ability.
**Example** **Example**
```ts ```ts
var caller; import Ability from '@ohos.app.ability.UIAbility';
export default class MainUIAbility extends UIAbility { let caller;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.context.startUIAbilityByCall({ this.context.startAbilityByCall({
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
abilityName: "MainUIAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
try { try {
...@@ -525,18 +530,19 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -525,18 +530,19 @@ Registers a callback that is invoked when the stub on the target ability is disc
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| | callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.|
**Example** **Example**
```ts ```ts
var caller; import Ability from '@ohos.application.Ability';
export default class MainUIAbility extends UIAbility { let caller;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.context.startUIAbilityByCall({ this.context.startAbilityByCall({
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
abilityName: "MainUIAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
try { try {
...@@ -544,7 +550,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -544,7 +550,7 @@ Registers a callback that is invoked when the stub on the target ability is disc
console.log(' Caller OnRelease CallBack is called ' + str); console.log(' Caller OnRelease CallBack is called ' + str);
}); });
} catch (error) { } catch (error) {
console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + console.log('Caller.onRelease catch error, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message)); ' error.message: ' + JSON.stringify(error.message));
} }
}).catch((err) => { }).catch((err) => {
...@@ -557,7 +563,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -557,7 +563,7 @@ Registers a callback that is invoked when the stub on the target ability is disc
## Caller.on ## Caller.on
on(type: "release", callback: OnReleaseCallback): void; on(type: 'release', callback: OnReleaseCallback): void;
Registers a callback that is invoked when the stub on the target ability is disconnected. Registers a callback that is invoked when the stub on the target ability is disconnected.
...@@ -568,7 +574,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -568,7 +574,7 @@ Registers a callback that is invoked when the stub on the target ability is disc
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.| | type | string | Yes| Event type. The value is fixed at **release**.|
| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| | callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.|
**Error codes** **Error codes**
...@@ -581,17 +587,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -581,17 +587,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
var caller; import Ability from '@ohos.app.ability.UIAbility';
export default class MainUIAbility extends UIAbility { let caller;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
this.context.startUIAbilityByCall({ this.context.startAbilityByCall({
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
abilityName: "MainUIAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}).then((obj) => { }).then((obj) => {
caller = obj; caller = obj;
try { try {
caller.on("release", (str) => { caller.on('release', (str) => {
console.log(' Caller OnRelease CallBack is called ' + str); console.log(' Caller OnRelease CallBack is called ' + str);
}); });
} catch (error) { } catch (error) {
...@@ -606,6 +613,108 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -606,6 +613,108 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
} }
``` ```
## Caller.off
off(type: 'release', callback: OnReleaseCallback): void;
Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
| callback | [OnReleaseCallBack](#onreleasecallback) | 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).
**Example**
```ts
let caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
let onReleaseCallBack = (str) => {
console.log(' Caller OnRelease CallBack is called ' + str);
};
caller.on('release', onReleaseCallBack);
caller.off('release', onReleaseCallBack);
} catch (error) {
console.log('Caller.on or Caller.off catch error, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
}).catch((err) => {
console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) +
' error.message: ' + JSON.stringify(err.message));
});
}
}
```
## Caller.off
off(type: 'release'): void;
Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **release**.|
**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).
**Example**
```ts
let caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
let onReleaseCallBack = (str) => {
console.log(' Caller OnRelease CallBack is called ' + str);
};
caller.on('release', onReleaseCallBack);
caller.off('release');
} catch (error) {
console.error('Caller.on or Caller.off catch error, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
}
}).catch((err) => {
console.error('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) +
' error.message: ' + JSON.stringify(err.message));
});
}
}
```
## Callee ## Callee
...@@ -624,7 +733,7 @@ Registers a caller notification callback, which is invoked when the target abili ...@@ -624,7 +733,7 @@ Registers a caller notification callback, which is invoked when the target abili
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.| | 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.| | callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.|
**Error codes** **Error codes**
...@@ -637,9 +746,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -637,9 +746,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{ class MyMessageAble{
name:"" name:''
str:"" str:''
num: 1 num: 1
constructor(name, str) { constructor(name, str) {
this.name = name; this.name = name;
...@@ -658,14 +768,14 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -658,14 +768,14 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
return true; return true;
} }
}; };
var method = 'call_Function'; let method = 'call_Function';
function funcCallBack(pdata) { function funcCallBack(pdata) {
console.log('Callee funcCallBack is called ' + pdata); console.log('Callee funcCallBack is called ' + pdata);
let msg = new MyMessageAble("test", ""); let msg = new MyMessageAble('test', '');
pdata.readSequenceable(msg); pdata.readSequenceable(msg);
return new MyMessageAble("test1", "Callee test"); return new MyMessageAble('test1', 'Callee test');
} }
export default class MainUIAbility extends UIAbility { export default class MainAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log('Callee onCreate is called'); console.log('Callee onCreate is called');
try { try {
...@@ -704,8 +814,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -704,8 +814,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example** **Example**
```ts ```ts
var method = 'call_Function'; import Ability from '@ohos.app.ability.UIAbility';
export default class MainUIAbility extends UIAbility { let method = 'call_Function';
export default class MainAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log('Callee onCreate is called'); console.log('Callee onCreate is called');
try { try {
...@@ -736,4 +847,4 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -736,4 +847,4 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
| Name| Readable| Writable| Type| Description| | Name| Readable| Writable| Type| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (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.| | (indata: [rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.|
...@@ -18,119 +18,118 @@ import Want from '@ohos.app.ability.Want'; ...@@ -18,119 +18,118 @@ import Want from '@ohos.app.ability.Want';
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | | deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name of 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. |
| 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.| | 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.|
| [action](js-apis-app-ability-wantConstant.md#wantconstantaction) | 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). | | uri | string | No| If **uri** is specified in a **Want**, the **Want** will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path** components.|
| [entities](js-apis-app-ability-wantConstant.md#wantconstantentity) | 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.| | 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.|
| 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**.| | flags | number | No| How the **Want** object will be handled. By default, a number is passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags). |
| 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.| | 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-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | | 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.<br>- **component.startup.newRules**: whether to enable the new control rule.<br/>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br/>- **ohos.dlp.params.sandbox**: available only for DLP files. |
| [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.| | 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.|
| moduleName | string | ·ñ | Module to which the ability belongs. |
**Example** **Example**
- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). - Basic usage
```ts ```ts
let want = { let want = {
"deviceId": "", // An empty deviceId indicates the local device. 'deviceId': '', // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication", 'bundleName': 'com.extreme.test',
"abilityName": "FuncAbility", 'abilityName': 'MainAbility',
"moduleName": "entry" // moduleName is optional. 'moduleName': 'entry' // moduleName is optional
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code);
}) })
``` ```
- 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): - Data is transferred through user-defined fields. The following data types are supported:
* String * String
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "FuncAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForString: "str", keyForString: 'str',
}, },
} };
``` ```
* Number * Number
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "FuncAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForInt: 100, keyForInt: 100,
keyForDouble: 99.99, keyForDouble: 99.99,
}, },
} };
``` ```
* Boolean * Boolean
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "FuncAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForBool: true, keyForBool: true,
}, },
} };
``` ```
* Object * Object
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "FuncAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForObject: { keyForObject: {
keyForObjectString: "str", keyForObjectString: 'str',
keyForObjectInt: -200, keyForObjectInt: -200,
keyForObjectDouble: 35.5, keyForObjectDouble: 35.5,
keyForObjectBool: false, keyForObjectBool: false,
}, },
}, },
} };
``` ```
* Array * Array
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "FuncAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForArrayString: ["str1", "str2", "str3"], keyForArrayString: ['str1', 'str2', 'str3'],
keyForArrayInt: [100, 200, 300, 400], keyForArrayInt: [100, 200, 300, 400],
keyForArrayDouble: [0.1, 0.2], keyForArrayDouble: [0.1, 0.2],
keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], keyForArrayObject: [{obj1: 'aaa'}, {obj2: 100}],
}, },
} };
``` ```
* File descriptor (FD) * File descriptor (FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync('/data/storage/el2/base/haps/pic.png');
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(e)); console.log('openSync fail:' + JSON.stringify(e));
}
let want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication",
"abilityName": "FuncAbility",
"moduleName": "entry", // moduleName is optional.
"parameters": {
"keyFd":{"type":"FD", "value":fd}
} }
}; let want = {
this.context.startAbility(want, (error) => { 'deviceId': '', // An empty deviceId indicates the local device.
'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility',
'moduleName': 'entry', // moduleName is optional.
'parameters': {
'keyFd':{'type':'FD', 'value':fd} // {'type':'FD', 'value':fd} is a fixed usage, indicating that the data is a file descriptor.
}
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code);
}) });
``` ```
- For more details and examples, see [Want](../../application-models/want-overview.md).
# @ohos.app.ability.wantAgent (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. The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future.
> **NOTE** > **NOTE**
> >
...@@ -8,7 +8,7 @@ The **app.ability.WantAgent** module provides APIs for creating and comparing ** ...@@ -8,7 +8,7 @@ The **app.ability.WantAgent** module provides APIs for creating and comparing **
## Modules to Import ## Modules to Import
```ts ```js
import WantAgent from '@ohos.app.ability.wantAgent'; import WantAgent from '@ohos.app.ability.wantAgent';
``` ```
...@@ -16,7 +16,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; ...@@ -16,7 +16,7 @@ import WantAgent from '@ohos.app.ability.wantAgent';
getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>): void getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>): void
Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -27,45 +27,22 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return ...@@ -27,45 +27,22 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return
| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | | info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. |
| callback | AsyncCallback\<WantAgent\> | Yes | Callback used to return the **WantAgent** object.| | callback | AsyncCallback\<WantAgent\> | Yes | Callback used to return the **WantAgent** object.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
let wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -85,20 +62,12 @@ let wantAgentInfo = { ...@@ -85,20 +62,12 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(err));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) { } catch (paramError) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -108,7 +77,7 @@ try { ...@@ -108,7 +77,7 @@ try {
getWantAgent(info: WantAgentInfo): Promise\<WantAgent\> getWantAgent(info: WantAgentInfo): Promise\<WantAgent\>
Obtains a **WantAgent** object. This API uses a promise to return the result. Obtains a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -124,43 +93,19 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. ...@@ -124,43 +93,19 @@ Obtains a **WantAgent** object. This API uses a promise to return the result.
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<WantAgent\> | Promise used to return the **WantAgent** object.| | Promise\<WantAgent\> | Promise used to return the **WantAgent** object.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
import WantAgent from '@ohos.app.ability.wantAgent';
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -180,16 +125,14 @@ let wantAgentInfo = { ...@@ -180,16 +125,14 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
try { try {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
wantAgent = data; console.info('==========================>getWantAgentCallback=======================>');
}).catch((err) => { });
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } catch (paramError) {
}); console.log('error: ' + paramError.code + ', ' + paramError.message);
} catch (err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
``` ```
...@@ -210,45 +153,31 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous ...@@ -210,45 +153,31 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<string\> | Yes | Callback used to return the bundle name.| | callback | AsyncCallback\<string\> | Yes | Callback used to return the bundle name.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
//getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -268,33 +197,18 @@ let wantAgentInfo = { ...@@ -268,33 +197,18 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getBundleName callback // getBundleName callback
function getBundleNameCallback(err, data) { function getBundleNameCallback(err, data) {
if(err) { console.info('==========================>getBundleNameCallback=======================>');
console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('getBundleName ok!' + JSON.stringify(data));
}
}
try {
WantAgent.getBundleName(wantAgent, getBundleNameCallback);
} catch(err) {
console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
} WantAgent.getBundleName(wantAgent, getBundleNameCallback);
try { } catch (paramError) {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); console.log('error: ' + paramError.code + ', ' + paramError.message);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
``` ```
...@@ -320,45 +234,22 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re ...@@ -320,45 +234,22 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<string\> | Promise used to return the bundle name.| | Promise\<string\> | Promise used to return the bundle name.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object
//WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -378,29 +269,19 @@ let wantAgentInfo = { ...@@ -378,29 +269,19 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
}
try {
WantAgent.getBundleName(wantAgent).then((data)=>{
console.info('getBundleName ok!' + JSON.stringify(data));
}).catch((err)=>{
console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.getBundleName(wantAgent).then((data) => {
console.info('==========================>getBundleNameCallback=======================>');
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -421,46 +302,31 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal ...@@ -421,46 +302,31 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<number\> | Yes | Callback used to return the user ID.| | callback | AsyncCallback\<number\> | Yes | Callback used to return the user ID.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
import WantAgent from '@ohos.app.ability.wantAgent'; import WantAgent from '@ohos.app.ability.wantAgent';
// WantAgent object
// wantAgent object
let wantAgent; let wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -480,33 +346,18 @@ let wantAgentInfo = { ...@@ -480,33 +346,18 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(err));
}
// getUid callback // getUid callback
function getUidCallback(err, data) { function getUidCallback(err, data) {
if(err) { console.info('==========================>getUidCallback=======================>');
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('getUid ok!' + JSON.stringify(data));
}
}
try {
WantAgent.getUid(wantAgent, getUidCallback);
} catch(err) {
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
} WantAgent.getUid(wantAgent, getUidCallback);
try { } catch (paramError) {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); console.log('error: ' + paramError.code + ', ' + paramError.message);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
``` ```
...@@ -532,45 +383,22 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return ...@@ -532,45 +383,22 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<number\> | Promise used to return the user ID.| | Promise\<number\> | Promise used to return the user ID.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -590,33 +418,24 @@ let wantAgentInfo = { ...@@ -590,33 +418,24 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
}
try {
WantAgent.getUid(wantAgent).then((data)=>{
console.info('getUid ok!' + JSON.stringify(data));
}).catch((err)=>{
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.getUid(wantAgent).then((data) => {
console.info('==========================>getUidCallback=======================>');
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## WantAgent.getWant ## WantAgent.getWant
getWant(agent: WantAgent, callback: AsyncCallback\<Want\>): void getWant(agent: WantAgent, callback: AsyncCallback\<Want\>): void
...@@ -634,45 +453,31 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba ...@@ -634,45 +453,31 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.| | callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -692,33 +497,18 @@ let wantAgentInfo = { ...@@ -692,33 +497,18 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getUid callback
function getWantCallback(err, data) {
if(err) {
console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('getWant ok!' + JSON.stringify(data));
}
}
try {
WantAgent.getWant(wantAgent, getBundleNameCallback);
} catch(err) {
console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); // getWant callback
function getWantCallback(err, data) {
console.info('==========================>getWantCallback=======================>');
}
WantAgent.getWant(wantAgent, getWantCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -746,45 +536,22 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th ...@@ -746,45 +536,22 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<Want\> | Promise used to return the want.| | Promise\<Want\> | Promise used to return the want.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -804,29 +571,19 @@ let wantAgentInfo = { ...@@ -804,29 +571,19 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
}
try {
WantAgent.getUid(wantAgent).then((data)=>{
console.info('getUid ok!' + JSON.stringify(data));
}).catch((err)=>{
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.getWant(wantAgent).then((data) => {
console.info('==========================>getWantCallback=======================>');
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -847,45 +604,31 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return ...@@ -847,45 +604,31 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -905,33 +648,18 @@ let wantAgentInfo = { ...@@ -905,33 +648,18 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getUid callback
function cancelCallback(err, data) {
if(err) {
console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('cancel ok!');
}
}
try {
WantAgent.cancel(wantAgent, getBundleNameCallback);
} catch(err) {
console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); // cancel callback
function cancelCallback(err, data) {
console.info('==========================>cancelCallback=======================>');
}
WantAgent.cancel(wantAgent, cancelCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -957,45 +685,22 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. ...@@ -957,45 +685,22 @@ Cancels a **WantAgent** object. This API uses a promise to return the result.
| --------------- | ------------------------------- | | --------------- | ------------------------------- |
| Promise\<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1015,32 +720,24 @@ let wantAgentInfo = { ...@@ -1015,32 +720,24 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
}
try {
WantAgent.cancel(wantAgent).then((data)=>{
console.info('cancel ok!');
}).catch((err)=>{
console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.cancel(wantAgent).then((data) => {
console.info('==========================>cancelCallback=======================>');
});
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
## WantAgent.trigger ## WantAgent.trigger
trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\<CompleteData\>): void trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\<CompleteData\>): void
...@@ -1054,52 +751,33 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur ...@@ -1054,52 +751,33 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ----------------------------- | ---- | ------------------------------- | | ----------- | ----------------------------- | ---- | ------------------------------- |
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | | triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. |
| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.| | callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** ```js
import WantAgent from '@ohos.app.ability.wantAgent';
```ts // wantAgent object
// WantAgent object
let wantAgent; let wantAgent;
// triggerInfo
let triggerInfo = { // getWantAgent callback
code: 0 // Custom result code. function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent = data;
} else {
console.info('----getWantAgent failed!----');
} }
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1119,33 +797,23 @@ let wantAgentInfo = { ...@@ -1119,33 +797,23 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getUid callback
function triggerCallback(err, data) {
if(err) {
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('getUid ok!' + JSON.stringify(data));
}
}
try {
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback);
} catch(err) {
console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); // trigger callback
function triggerCallback(data) {
console.info('==========================>triggerCallback=======================>');
}
let triggerInfo = {
code:0
};
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -1167,46 +835,33 @@ Checks whether two **WantAgent** objects are equal to determine whether the same ...@@ -1167,46 +835,33 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
| otherAgent | WantAgent | Yes | The second **WantAgent** object. | | otherAgent | WantAgent | Yes | The second **WantAgent** object. |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent1; let wantAgent1;
let wantAgent2; let wantAgent2;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info('==========================>getWantAgentCallback=======================>');
if (err.code == 0) {
wantAgent1 = data;
wantAgent2 = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1226,34 +881,18 @@ let wantAgentInfo = { ...@@ -1226,34 +881,18 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent1 = data;
wantAgent2 = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getUid callback
function equalCallback(err, data) {
if(err) {
console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('equal ok!' + JSON.stringify(data));
}
}
try {
WantAgent.equal(wantAgent1,wantAgent2,equalCallback);
} catch(err) {
console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); // equal callback
function equalCallback(err, data) {
console.info('==========================>equalCallback=======================>');
}
WantAgent.equal(wantAgent1, wantAgent2, equalCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -1280,46 +919,23 @@ Checks whether two **WantAgent** objects are equal to determine whether the same ...@@ -1280,46 +919,23 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result.| | Promise\<boolean\> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent1; let wantAgent1;
let wantAgent2; let wantAgent2;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1339,30 +955,20 @@ let wantAgentInfo = { ...@@ -1339,30 +955,20 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback try {
function getWantAgentCallback(err, data) { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
if (err === undefined) { console.info('==========================>getWantAgentCallback=======================>');
wantAgent1 = data; wantAgent1 = data;
wantAgent2 = data; wantAgent2 = data;
} else { });
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
} WantAgent.equal(wantAgent1, wantAgent2).then((data) => {
try { console.info('==========================>equalCallback=======================>');
WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ });
console.info('equal ok!' + JSON.stringify(data)); } catch (paramError) {
}).catch((err)=>{ console.log('error: ' + paramError.code + ', ' + paramError.message);
console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} }
``` ```
...@@ -1381,45 +987,21 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron ...@@ -1381,45 +987,21 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron
| agent | WantAgent | Yes | Target **WantAgent** object. | | agent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the operation type.| | callback | AsyncCallback\<number> | Yes | Callback used to return the operation type.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1439,33 +1021,19 @@ let wantAgentInfo = { ...@@ -1439,33 +1021,19 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed' + JSON.stringify(wantAgent));
}
// getUid callback
function getOperationTypeCallback(err, data) {
if(err) {
console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
} else {
console.info('getOperationType ok!' + JSON.stringify(data));
}
}
try {
WantAgent.getOperationTypeCallback(wantAgent, getBundleNameCallback);
} catch(err) {
console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.getOperationType(wantAgent, (OperationType) => {
console.log('----------- getOperationType ----------, OperationType: ' + OperationType);
})
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -1489,45 +1057,21 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to ...@@ -1489,45 +1057,21 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to
| ----------------------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<number> | Promise used to return the operation type.| | Promise\<number> | Promise used to return the operation type.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example** **Example**
```ts ```js
// WantAgent object import WantAgent from '@ohos.app.ability.wantAgent';
// wantAgent object
let wantAgent; let wantAgent;
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: 'deviceId', deviceId: 'deviceId',
bundleName: 'com.example.myapplication', bundleName: 'com.neu.setResultOnAbilityResultTest1',
abilityName: 'EntryAbility', abilityName: 'com.example.test.MainAbility',
action: 'action1', action: 'action1',
entities: ['entity1'], entities: ['entity1'],
type: 'MIMETYPE', type: 'MIMETYPE',
...@@ -1547,29 +1091,21 @@ let wantAgentInfo = { ...@@ -1547,29 +1091,21 @@ let wantAgentInfo = {
operationType: WantAgent.OperationType.START_ABILITIES, operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0, requestCode: 0,
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
} };
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.info('getWantAgent failed!' + JSON.stringify(wantAgent));
}
try {
WantAgent.getOperationType(wantAgent).then((data)=>{
console.info('getOperationType ok!' + JSON.stringify(data));
}).catch((err)=>{
console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
})
} catch(err){
console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message));
}
}
try { try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); WantAgent.getWantAgent(wantAgentInfo).then((data) => {
} catch(err) { console.info('==========================>getWantAgentCallback=======================>');
console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); wantAgent = data;
});
WantAgent.getOperationType(wantAgent).then((OperationType) => {
console.log('getOperationType success, OperationType: ' + OperationType);
}).catch((err) => {
console.log('getOperationType fail, err: ' + err);
})
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
} }
``` ```
...@@ -1615,5 +1151,6 @@ try { ...@@ -1615,5 +1151,6 @@ try {
| info | WantAgent | Yes | A triggered **WantAgent** object. | | info | WantAgent | Yes | A triggered **WantAgent** object. |
| want | Want | Yes | An existing triggered **want**. | | want | Want | Yes | An existing triggered **want**. |
| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| | finalCode | number | Yes | Request code that triggers the **WantAgent** object.|
| finalData | string | No | Final data collected by the common event. | | finalData | string | Yes | Final data collected by the common event. |
| extraInfo | {[key: string]: any} | No | Extra information. | | extraInfo | {[key: string]: any} | No | Extra information. |
...@@ -8,7 +8,7 @@ The **wantConstant** module provides the actions, entities, and flags used in ** ...@@ -8,7 +8,7 @@ The **wantConstant** module provides the actions, entities, and flags used in **
## Modules to Import ## Modules to Import
```js ```ts
import wantConstant from '@ohos.app.ability.wantConstant'; import wantConstant from '@ohos.app.ability.wantConstant';
``` ```
...@@ -79,4 +79,4 @@ Enumerates the entity constants of the **Want** object. **entity** specifies add ...@@ -79,4 +79,4 @@ Enumerates the entity constants of the **Want** object. **entity** specifies add
| ------------------------------------ | ---------- | ------------------------------------------------------------ | | ------------------------------------ | ---------- | ------------------------------------------------------------ |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | | 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_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
...@@ -35,7 +35,7 @@ Creates a **FormBindingData** object. ...@@ -35,7 +35,7 @@ Creates a **FormBindingData** object.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | -------------- | ---- | ------------------------------------------------------------ | | ------ | -------------- | ---- | ------------------------------------------------------------ |
| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| | obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.|
**Return value** **Return value**
...@@ -48,17 +48,20 @@ Creates a **FormBindingData** object. ...@@ -48,17 +48,20 @@ Creates a **FormBindingData** object.
**Example** **Example**
```ts ```ts
import fs from '@ohos.file.fs'; import featureAbility from '@ohos.ability.featureAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
try { context.getOrCreateLocalDir((err,data)=>{
let fd = fs.openSync('/path/to/form.png') let path=data+'/xxx.jpg';
let fd = fileio.openSync(path);
let obj = { let obj = {
"temperature": "21°", 'temperature': '21°',
"formImages": { "image": fd } 'formImages': {'image': fd}
}; };
formBindingData.createFormBindingData(obj); try {
} catch (error) { formBindingData.createFormBindingData(obj);
console.log(`catch error, code: ${error.code}, message: ${error.message}`); } catch (error) {
} console.log(`catch err->${JSON.stringify(err)}`);
}
})
``` ```
# @ohos.app.form.formHost (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** > **NOTE**
> >
...@@ -34,26 +34,25 @@ Deletes a widget. After this API is called, the application can no longer use th ...@@ -34,26 +34,25 @@ Deletes a widget. After this API is called, the application can no longer use th
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.deleteForm(formId, (error) => { formHost.deleteForm(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost deleteForm, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
## deleteForm ## deleteForm
...@@ -83,23 +82,21 @@ Deletes a widget. After this API is called, the application can no longer use th ...@@ -83,23 +82,21 @@ Deletes a widget. After this API is called, the application can no longer use th
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Parameters** **Parameters**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.deleteForm(formId).then(() => { formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost deleteForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -124,23 +121,21 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -124,23 +121,21 @@ Releases a widget. After this API is called, the application can no longer use t
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.releaseForm(formId, (error) => { formHost.releaseForm(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost releaseForm, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -166,23 +161,21 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -166,23 +161,21 @@ Releases a widget. After this API is called, the application can no longer use t
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.releaseForm(formId, true, (error) => { formHost.releaseForm(formId, true, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost releaseForm, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -213,23 +206,21 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -213,23 +206,21 @@ Releases a widget. After this API is called, the application can no longer use t
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.releaseForm(formId, true).then(() => { formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success'); console.log('formHost releaseForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost releaseForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -254,23 +245,21 @@ Requests a widget update. This API uses an asynchronous callback to return the r ...@@ -254,23 +245,21 @@ Requests a widget update. This API uses an asynchronous callback to return the r
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.requestForm(formId, (error) => { formHost.requestForm(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost requestForm, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -300,23 +289,21 @@ Requests a widget update. This API uses a promise to return the result. ...@@ -300,23 +289,21 @@ Requests a widget update. This API uses a promise to return the result.
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.requestForm(formId).then(() => { formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success'); console.log('formHost requestForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost requestForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -342,23 +329,21 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb ...@@ -342,23 +329,21 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.castToNormalForm(formId, (error) => { formHost.castToNormalForm(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost castTempForm, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -388,23 +373,21 @@ Converts a temporary widget to a normal one. This API uses a promise to return t ...@@ -388,23 +373,21 @@ Converts a temporary widget to a normal one. This API uses a promise to return t
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = "12400633174999288"; var formId = '12400633174999288';
formHost.castToNormalForm(formId).then(() => { formHost.castToNormalForm(formId).then(() => {
console.log('formHost castTempForm success'); console.log('formHost castTempForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost castTempForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -429,23 +412,21 @@ Instructs the widget framework to make a widget visible. After this API is calle ...@@ -429,23 +412,21 @@ Instructs the widget framework to make a widget visible. After this API is calle
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.notifyVisibleForms(formId, (error) => { formHost.notifyVisibleForms(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -475,23 +456,21 @@ Instructs the widget framework to make a widget visible. After this API is calle ...@@ -475,23 +456,21 @@ Instructs the widget framework to make a widget visible. After this API is calle
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.notifyVisibleForms(formId).then(() => { formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success'); console.log('formHost notifyVisibleForms success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -516,23 +495,21 @@ Instructs the widget framework to make a widget invisible. After this API is cal ...@@ -516,23 +495,21 @@ Instructs the widget framework to make a widget invisible. After this API is cal
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.notifyInvisibleForms(formId, (error) => { formHost.notifyInvisibleForms(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -562,23 +539,21 @@ Instructs the widget framework to make a widget invisible. After this API is cal ...@@ -562,23 +539,21 @@ Instructs the widget framework to make a widget invisible. After this API is cal
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.notifyInvisibleForms(formId).then(() => { formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success'); console.log('formHost notifyInvisibleForms success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -603,23 +578,21 @@ Instructs the widget framework to make a widget updatable. After this API is cal ...@@ -603,23 +578,21 @@ Instructs the widget framework to make a widget updatable. After this API is cal
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.enableFormsUpdate(formId, (error) => { formHost.enableFormsUpdate(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -649,23 +622,21 @@ Instructs the widget framework to make a widget updatable. After this API is cal ...@@ -649,23 +622,21 @@ Instructs the widget framework to make a widget updatable. After this API is cal
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.enableFormsUpdate(formId).then(() => { formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success'); console.log('formHost enableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -690,23 +661,21 @@ Instructs the widget framework to make a widget not updatable. After this API is ...@@ -690,23 +661,21 @@ Instructs the widget framework to make a widget not updatable. After this API is
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.disableFormsUpdate(formId, (error) => { formHost.disableFormsUpdate(formId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -736,23 +705,21 @@ Instructs the widget framework to make a widget not updatable. After this API is ...@@ -736,23 +705,21 @@ Instructs the widget framework to make a widget not updatable. After this API is
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formId = ["12400633174999288"]; var formId = ['12400633174999288'];
formHost.disableFormsUpdate(formId).then(() => { formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success'); console.log('formHost disableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -773,16 +740,15 @@ Checks whether the system is ready. This API uses an asynchronous callback to re ...@@ -773,16 +740,15 @@ Checks whether the system is ready. This API uses an asynchronous callback to re
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
var formId = '12400633174999288';
formHost.isSystemReady((error, data) => { formHost.isSystemReady((error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost isSystemReady, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -803,16 +769,15 @@ Checks whether the system is ready. This API uses a promise to return the result ...@@ -803,16 +769,15 @@ Checks whether the system is ready. This API uses a promise to return the result
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
var formId = '12400633174999288';
formHost.isSystemReady().then(() => { formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success'); console.log('formHost isSystemReady success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost isSystemReady, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -830,23 +795,21 @@ Obtains the widget information provided by all applications on the device. This ...@@ -830,23 +795,21 @@ Obtains the widget information provided by all applications on the device. This
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| 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.| | 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, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
formHost.getAllFormsInfo((error, data) => { formHost.getAllFormsInfo((error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -864,21 +827,19 @@ Obtains the widget information provided by all applications on the device. This ...@@ -864,21 +827,19 @@ Obtains the widget information provided by all applications on the device. This
| Type | Description | | Type | Description |
| :----------------------------------------------------------- | :---------------------------------- | | :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
formHost.getAllFormsInfo().then((data) => { formHost.getAllFormsInfo().then((data) => {
console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -903,24 +864,22 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -903,24 +864,22 @@ Obtains the widget information provided by a given application on the device. Th
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -946,24 +905,22 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -946,24 +905,22 @@ Obtains the widget information provided by a given application on the device. Th
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -988,28 +945,26 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -988,28 +945,26 @@ Obtains the widget information provided by a given application on the device. Th
| Type | Description | | Type | Description |
| :----------------------------------------------------------- | :---------------------------------- | | :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data) => {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1033,19 +988,17 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to ...@@ -1033,19 +988,17 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formIds = new Array("12400633174999288", "12400633174999289"); var formIds = new Array('12400633174999288', '12400633174999289');
formHost.deleteInvalidForms(formIds, (error, data) => { formHost.deleteInvalidForms(formIds, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1074,17 +1027,15 @@ Deletes invalid widgets from the list. This API uses a promise to return the res ...@@ -1074,17 +1027,15 @@ Deletes invalid widgets from the list. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
try { try {
let formIds = new Array("12400633174999288", "12400633174999289"); var formIds = new Array('12400633174999288', '12400633174999289');
formHost.deleteInvalidForms(formIds).then((data) => { formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1103,40 +1054,38 @@ Obtains the widget state. This API uses an asynchronous callback to return the r ...@@ -1103,40 +1054,38 @@ Obtains the widget state. This API uses an asynchronous callback to return the r
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| 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.| | 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.| | callback | AsyncCallback&lt;[FormInfo](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 codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var want = {
'deviceId': '',
let want = { 'bundleName': 'ohos.samples.FormApplication',
"deviceId": "", 'abilityName': 'FormAbility',
"bundleName": "ohos.samples.FormApplication", 'parameters': {
"abilityName": "FormAbility", 'ohos.extra.param.key.module_name': 'entry',
"parameters": { 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry", 'ohos.extra.param.key.form_dimension': 2
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.form_dimension": 2
} }
}; };
try { try {
formHost.acquireFormState(want, (error, data) => { formHost.acquireFormState(want, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost acquireFormState, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1160,44 +1109,42 @@ Obtains the widget state. This API uses a promise to return the result. ...@@ -1160,44 +1109,42 @@ Obtains the widget state. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise used to return the widget state obtained.| | Promise&lt;[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise used to return the widget state obtained.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var want = {
'deviceId': '',
let want = { 'bundleName': 'ohos.samples.FormApplication',
"deviceId": "", 'abilityName': 'FormAbility',
"bundleName": "ohos.samples.FormApplication", 'parameters': {
"abilityName": "FormAbility", 'ohos.extra.param.key.module_name': 'entry',
"parameters": { 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry", 'ohos.extra.param.key.form_dimension': 2
"ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.form_dimension": 2
} }
}; };
try { try {
formHost.acquireFormState(want).then((data) => { formHost.acquireFormState(want).then((data) => {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost acquireFormState, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
## on("formUninstall") ## on('formUninstall')
on(type: "formUninstall", callback: Callback&lt;string&gt;): void on(type: 'formUninstall', callback: Callback&lt;string&gt;): void
Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result.
...@@ -1207,23 +1154,21 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to ...@@ -1207,23 +1154,21 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| | type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.|
| callback | Callback&lt;string&gt; | Yes| Callback used to return the widget ID.| | callback | Callback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
let callback = function(formId) { let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId); console.log('formHost on formUninstall, formId:' + formId);
} }
formHost.on("formUninstall", callback); formHost.on('formUninstall', callback);
``` ```
## off("formUninstall") ## off('formUninstall')
off(type: "formUninstall", callback?: Callback&lt;string&gt;): void off(type: 'formUninstall', callback?: Callback&lt;string&gt;): void
Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result.
...@@ -1233,18 +1178,16 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac ...@@ -1233,18 +1178,16 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| | 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.<br> The value must be the same as that in **on("formUninstall")**.| | 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** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost';
let callback = function(formId) { let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId); console.log('formHost on formUninstall, formId:' + formId);
} }
formHost.off("formUninstall", callback); formHost.off('formUninstall', callback);
``` ```
## notifyFormsVisible ## notifyFormsVisible
...@@ -1269,23 +1212,21 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous ...@@ -1269,23 +1212,21 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsVisible(formIds, true, (error) => { formHost.notifyFormsVisible(formIds, true, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1316,23 +1257,21 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret ...@@ -1316,23 +1257,21 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsVisible(formIds, true).then(() => { formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success'); console.log('formHost notifyFormsVisible success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1358,23 +1297,21 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou ...@@ -1358,23 +1297,21 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsEnableUpdate(formIds, true, (error) => { formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1405,23 +1342,21 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r ...@@ -1405,23 +1342,21 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsEnableUpdate(formIds, true).then(() => { formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success'); console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
## shareForm ## shareForm
...@@ -1446,24 +1381,23 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca ...@@ -1446,24 +1381,23 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formId = '12400633174999288';
var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try { try {
formHost.shareForm(formId, deviceId, (error) => { formHost.shareForm(formId, deviceId, (error, data) => {
if (error) { if (error) {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost shareForm, error:' + JSON.stringify(error));
} }
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1494,24 +1428,22 @@ Shares a specified widget with a remote device. This API uses a promise to retur ...@@ -1494,24 +1428,22 @@ Shares a specified widget with a remote device. This API uses a promise to retur
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.app.form.formHost'; var formId = '12400633174999288';
var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try { try {
formHost.shareForm(formId, deviceId).then(() => { formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost shareForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -1529,75 +1461,18 @@ Notifies that the privacy protection status of the specified widgets changes. Th ...@@ -1529,75 +1461,18 @@ Notifies that the privacy protection status of the specified widgets changes. Th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array\<string\> | Yes | ID of the widgets.| | formId | string | Yes | Widget ID.|
| isProtected | boolean | Yes | Whether privacy protection is enabled.| | deviceId | string | Yes | Remote device ID. |
| 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 ```ts
import formHost from '@ohos.app.form.formHost'; var formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost notifyFormsPrivacyProtected success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
console.log(`error, code: ${error.code}, message: ${error.message}`); console.log('formHost shareForm, error:' + JSON.stringify(error));
}); });
} catch(error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message}`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
# @ohos.app.form.formProvider (formProvider) # @ohos.app.form.formProvider (FormProvider)
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. 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,25 +31,23 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback ...@@ -31,25 +31,23 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; var formId = '12400633174999288';
let formId = "12400633174999288";
try { try {
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
} else { } else {
console.log(`formProvider setFormNextRefreshTime success`); console.log(`formProvider setFormNextRefreshTime success`);
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log('error' + JSON.stringify(error))
} }
``` ```
...@@ -78,23 +76,21 @@ Sets the next refresh time for a widget. This API uses a promise to return the r ...@@ -78,23 +76,21 @@ Sets the next refresh time for a widget. This API uses a promise to return the r
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; var formId = '12400633174999288';
let formId = "12400633174999288";
try { try {
formProvider.setFormNextRefreshTime(formId, 5).then(() => { formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log(`formProvider setFormNextRefreshTime success`); console.log('formProvider setFormNextRefreshTime success');
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -118,27 +114,25 @@ Updates a widget. This API uses an asynchronous callback to return the result. ...@@ -118,27 +114,25 @@ Updates a widget. This API uses an asynchronous callback to return the result.
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; var formId = '12400633174999288';
let formId = "12400633174999288";
try { try {
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
formProvider.updateForm(formId, obj, (error, data) => { formProvider.updateForm(formId, obj, (error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider updateForm, error:' + JSON.stringify(error));
} else { } else {
console.log(`formProvider updateForm success`); console.log(`formProvider updateForm success`);
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -167,25 +161,23 @@ Updates a widget. This API uses a promise to return the result. ...@@ -167,25 +161,23 @@ Updates a widget. This API uses a promise to return the result.
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; var formId = '12400633174999288';
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" });
try { try {
formProvider.updateForm(formId, obj).then(() => { formProvider.updateForm(formId, obj).then(() => {
console.log(`formProvider updateForm success`); console.log('formProvider updateForm success');
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider updateForm, error:' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -201,31 +193,29 @@ Obtains the application's widget information on the device. This API uses an asy ...@@ -201,31 +193,29 @@ Obtains the application's widget information on the device. This API uses an asy
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.getFormsInfo((error, data) => { formProvider.getFormsInfo((error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
## getFormsInfo ## getFormsInfo
...@@ -241,35 +231,33 @@ Obtains the application's widget information that meets a filter criterion on th ...@@ -241,35 +231,33 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formInfo from '@ohos.app.form.formInfo'; 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.
const filter: formInfo.FormInfoFilter = { moduleName : 'entry'
// get info of forms belong to module entry.
moduleName: "entry"
}; };
try { try {
formProvider.getFormsInfo(filter, (error, data) => { formProvider.getFormsInfo(filter, (error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch(error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -291,33 +279,31 @@ Obtains the application's widget information on the device. This API uses a prom ...@@ -291,33 +279,31 @@ Obtains the application's widget information on the device. This API uses a prom
| Type | Description | | Type | Description |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formInfo from '@ohos.app.form.formInfo'; 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.
const filter: formInfo.FormInfoFilter = { moduleName : 'entry'
// get info of forms belong to module entry.
moduleName: "entry"
}; };
try { try {
formProvider.getFormsInfo(filter).then((data) => { formProvider.getFormsInfo(filter).then((data) => {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -335,42 +321,40 @@ Requests to publish a widget carrying data to the widget host. This API uses an ...@@ -335,42 +321,40 @@ Requests to publish a widget carrying data to the widget host. This API uses an
| Name| Type | Mandatory| Description | | 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" | | 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.| | callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; var want = {
abilityName: 'FormAbility',
let want = {
abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
try { 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) => { formProvider.requestPublishForm(want, obj, (error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -388,40 +372,39 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c ...@@ -388,40 +372,39 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c
| Name | Type | Mandatory| Description | | 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" | | 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' |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the widget ID.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the widget ID.|
**Error codes** **Error codes**
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; var want = {
abilityName: 'FormAbility',
let want = {
abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
try { try {
formProvider.requestPublishForm(want, (error, data) => { formProvider.requestPublishForm(want, (error, data) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
## requestPublishForm ## requestPublishForm
...@@ -438,8 +421,8 @@ Requests to publish a widget to the widget host. This API uses a promise to retu ...@@ -438,8 +421,8 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Name | Type | Mandatory| Description | | 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" | | 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** **Return value**
...@@ -451,30 +434,28 @@ Requests to publish a widget to the widget host. This API uses a promise to retu ...@@ -451,30 +434,28 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Error Code ID| Error Message| | Error Code ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 401 | Incorrect input parameter.| | 401 | If the input parameter is not valid parameter. |
|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| |For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; var want = {
abilityName: 'FormAbility',
let want = {
abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
try { try {
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -497,38 +478,37 @@ Checks whether a widget can be published to the widget host. This API uses an as ...@@ -497,38 +478,37 @@ Checks whether a widget can be published to the widget host. This API uses an as
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.isRequestPublishFormSupported((error, isSupported) => { formProvider.isRequestPublishFormSupported((error, isSupported) => {
if (error) { if (error) {
console.log(`callback error, code: ${error.code}, message: ${error.message})`); console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
} else { } else {
if (isSupported) { if (isSupported) {
var want = { var want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
}
};
try {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}; });
try { } catch (error) {
formProvider.requestPublishForm(want, (error, data) => { console.log(`catch err->${JSON.stringify(error)}`);
if (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 error, code: ${error.code}, message: ${error.message})`);
}
} }
} }
}); }
});
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
...@@ -551,33 +531,32 @@ Checks whether a widget can be published to the widget host. This API uses a pro ...@@ -551,33 +531,32 @@ Checks whether a widget can be published to the widget host. This API uses a pro
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.isRequestPublishFormSupported().then((isSupported) => { formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) { if (isSupported) {
var want = { var want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
try { try {
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
} }
}).catch((error) => { }).catch((error) => {
console.log(`promise error, code: ${error.code}, message: ${error.message})`); console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
}); });
} catch (error) { } catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`); console.log(`catch err->${JSON.stringify(error)}`);
} }
``` ```
# @ohos.application.abilityDelegatorRegistry (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. 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. The APIs can be used only in the test framework.
> **NOTE** > **NOTE**
> >
> 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. > The 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 ## Modules to Import
...@@ -43,7 +43,7 @@ Obtains the **AbilityDelegator** object of the application. ...@@ -43,7 +43,7 @@ Obtains the **AbilityDelegator** object of the application.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
``` ```
...@@ -65,8 +65,8 @@ Obtains the **AbilityDelegatorArgs** object of the application. ...@@ -65,8 +65,8 @@ Obtains the **AbilityDelegatorArgs** object of the application.
**Example** **Example**
```ts ```ts
var args = AbilityDelegatorRegistry.getArguments(); let args = AbilityDelegatorRegistry.getArguments();
console.info("getArguments bundleName:" + args.bundleName); console.info('getArguments bundleName:' + args.bundleName);
console.info("getArguments testCaseNames:" + args.testCaseNames); console.info('getArguments testCaseNames:' + args.testCaseNames);
console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); console.info('getArguments testRunnerClassName:' + args.testRunnerClassName);
``` ```
...@@ -4,13 +4,13 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ...@@ -4,13 +4,13 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying
> **NOTE** > **NOTE**
> >
> 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 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 system APIs and cannot be called by third-party applications. > The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import ## Modules to Import
```ts ```ts
import abilityManager from '@ohos.application.abilityManager' import AbilityManager from '@ohos.application.abilityManager';
``` ```
## AbilityState ## AbilityState
...@@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the ...@@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -49,11 +49,13 @@ Updates the configuration. This API uses an asynchronous callback to return the ...@@ -49,11 +49,13 @@ Updates the configuration. This API uses an asynchronous callback to return the
**Example** **Example**
```ts ```ts
var config = { import abilitymanager from '@ohos.application.abilityManager';
let config = {
language: 'chinese' language: 'chinese'
} };
abilityManager.updateConfiguration(config, () => { abilitymanager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------'); console.log('------------ updateConfiguration -----------');
}) })
``` ```
...@@ -83,11 +85,13 @@ Updates the configuration. This API uses a promise to return the result. ...@@ -83,11 +85,13 @@ Updates the configuration. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var config = { import abilitymanager from '@ohos.application.abilityManager';
let config = {
language: 'chinese' language: 'chinese'
} };
abilityManager.updateConfiguration(config).then(() => { abilitymanager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success'); console.log('updateConfiguration success');
}).catch((err) => { }).catch((err) => {
console.log('updateConfiguration fail'); console.log('updateConfiguration fail');
...@@ -113,7 +117,9 @@ Obtains the ability running information. This API uses an asynchronous callback ...@@ -113,7 +117,9 @@ Obtains the ability running information. This API uses an asynchronous callback
**Example** **Example**
```ts ```ts
abilityManager.getAbilityRunningInfos((err,data) => { import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
}); });
``` ```
...@@ -137,116 +143,11 @@ Obtains the ability running information. This API uses a promise to return the r ...@@ -137,116 +143,11 @@ Obtains the ability running information. This API uses a promise to return the r
**Example** **Example**
```ts ```ts
abilityManager.getAbilityRunningInfos().then((data) => { import abilitymanager from '@ohos.application.abilityManager';
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
Obtains the extension running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| callback | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | Yes | Callback used to return the result. |
**Example**
```ts
var upperLimit = 0;
abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO abilitymanager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | Promise used to return the result.|
**Example**
```ts
var upperLimit = 0;
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log("getAbilityRunningInfos err: " + err); console.log("getAbilityRunningInfos err: " + err);
})
```
## getTopAbility<sup>9+</sup>
getTopAbility(callback: AsyncCallback\<ElementName>): void;
Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the result. |
**Example**
```ts
abilityManager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
}); });
``` ```
## getTopAbility<sup>9+</sup>
getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the result.|
**Example**
```ts
abilityManager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
})
```
...@@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API ...@@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API
## Modules to Import ## Modules to Import
```ts ```ts
import app from '@ohos.application.appManager'; import appManager from '@ohos.application.appManager';
``` ```
## appManager.isRunningInStabilityTest<sup>8+</sup> ## appManager.isRunningInStabilityTest<sup>8+</sup>
...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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.| | 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.|
**Example** **Example**
...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value** **Return value**
| Type| Description| | 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 result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value** **Return value**
| Type| Description| | 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 whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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.| | 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.|
**Example** **Example**
...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the memory size, in MB.| | Promise&lt;number&gt; | Promise used to return the memory size, in MB.|
**Example** **Example**
...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the memory size, in MB.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the memory size, in MB.|
**Example** **Example**
...@@ -199,7 +199,7 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -199,7 +199,7 @@ Obtains information about the running processes. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| 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.| | callback | AsyncCallback\<Array\<[ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)>> | Yes| Callback used to return the running processes. |
**Example** **Example**
......
# @ohos.application.Configuration (Configuration) # @ohos.application.Configuration (Configuration)
The **Configuration** module defines environment change information. The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration.
> **NOTE** > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > 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. > This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead.
## Modules to Import
```ts
import Configuration from '@ohos.application.Configuration'
```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| language<sup>8+</sup> | string | Yes| Yes| Language of the application, for example, **zh**.| | language<sup>8+</sup> | string | Yes| Yes| Language of the application.|
| colorMode<sup>8+</sup> | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| | colorMode<sup>8+</sup> | [ColorMode](js-apis-application-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<sup>9+</sup> | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.|
| screenDensity<sup>9+</sup> | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | 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.|
For details about the fields, see the **ohos.application.Configuration.d.ts** file. For details about the fields, see the **ohos.application.Configuration.d.ts** file.
**Example** **Example**
```ts ```ts
import hilog from '@ohos.hilog'; import Ability from '@ohos.application.Ability'
import UIAbility from '@ohos.app.ability.UIAbility'; import Window from '@ohos.window'
import Window from '@ohos.window';
export default class EntryAbility extends UIAbility { export default class MainAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
} }
...@@ -42,13 +31,9 @@ export default class EntryAbility extends UIAbility { ...@@ -42,13 +31,9 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: Window.WindowStage) { onWindowStageCreate(windowStage: Window.WindowStage) {
let envCallback = { let envCallback = {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`);
let language = config.language; let language = config.language;
let colorMode = config.colorMode; let colorMode = config.colorMode;
let direction = config.direction;
let screenDensity = config.screenDensity;
let displayId = config.displayId;
let hasPointerDevice = config.hasPointerDevice;
} }
}; };
...@@ -57,12 +42,10 @@ export default class EntryAbility extends UIAbility { ...@@ -57,12 +42,10 @@ export default class EntryAbility extends UIAbility {
windowStage.loadContent('pages/index', (err, data) => { windowStage.loadContent('pages/index', (err, data) => {
if (err.code) { if (err.code) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR); console.error('failed to load the content, error: + ${JSON.stringify(err)}');
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return; return;
} }
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); console.info('Succeeded in loading the content, data: + ${JSON.stringify(data)}');
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
}); });
} }
} }
......
...@@ -23,33 +23,3 @@ You can obtain the value of this constant by calling the **ConfigurationConstant ...@@ -23,33 +23,3 @@ You can obtain the value of this constant by calling the **ConfigurationConstant
| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| | COLOR_MODE_NOT_SET | -1 | Unspecified color mode.|
| COLOR_MODE_DARK | 0 | Dark mode.| | COLOR_MODE_DARK | 0 | Dark mode.|
| COLOR_MODE_LIGHT | 1 | Light mode.| | COLOR_MODE_LIGHT | 1 | Light mode.|
## ConfigurationConstant.Direction<sup>9+</sup>
You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API.
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Value| Description|
| -------- | -------- | -------- |
| DIRECTION_NOT_SET | -1 | Unspecified direction.|
| DIRECTION_VERTICAL | 0 | Vertical direction.|
| DIRECTION_HORIZONTAL | 1 | Horizontal direction.|
## ConfigurationConstant.ScreenDensity<sup>9+</sup>
You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API.
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Value| Description|
| -------- | -------- | -------- |
| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.|
| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.|
| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.|
| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.|
| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.|
| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.|
| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.|
# @ohos.application.EnvironmentCallback (EnvironmentCallback) # @ohos.application.EnvironmentCallback (EnvironmentCallback)
The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated** and **onMemoryLevel**, for the application context to listen for system environment changes. The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated**, for the application context to listen for system environment changes.
> **NOTE** > **NOTE**
> >
> 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 are supported and deprecated in 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. > The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
```ts ```ts
import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; import EnvironmentCallback from '@ohos.application.EnvironmentCallback';
``` ```
...@@ -30,48 +30,32 @@ Called when the system environment changes. ...@@ -30,48 +30,32 @@ Called when the system environment changes.
| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| | config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.|
## EnvironmentCallback.onMemoryLevel ## 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 ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.application.Ability';
var callbackId; let callbackId;
export default class EntryAbility extends UIAbility { export default class MyAbility extends Ability {
onCreate() { onCreate() {
console.log("MyAbility onCreate") console.log('MyAbility onCreate');
globalThis.applicationContext = this.context.getApplicationContext(); globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = { let EnvironmentCallback = {
onConfigurationUpdated(config){ onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config)); console.log('onConfigurationUpdated config:' + JSON.stringify(config));
}, },
onMemoryLevel(level){ };
console.log("onMemoryLevel level:" + level);
}
}
// 1. Obtain an applicationContext object. // 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
// 2. Register a listener for the environment changes through the applicationContext object. // 2. Register a listener for the environment changes through the applicationContext object.
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId));
} }
onDestroy() { onDestroy() {
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
}); });
} }
} }
......
...@@ -35,7 +35,7 @@ Creates a **FormBindingData** object. ...@@ -35,7 +35,7 @@ Creates a **FormBindingData** object.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | -------------- | ---- | ------------------------------------------------------------ | | ------ | -------------- | ---- | ------------------------------------------------------------ |
| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| | obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.|
**Return value** **Return value**
...@@ -48,17 +48,16 @@ Creates a **FormBindingData** object. ...@@ -48,17 +48,16 @@ Creates a **FormBindingData** object.
**Example** **Example**
```ts ```ts
import formBindingData from @ohos.application.formBindingData; import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs'; import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
try { context.getOrCreateLocalDir((err,data)=>{
let fd = fs.openSync('/path/to/form.png') let path=data+'/xxx.jpg';
let fd = fileio.openSync(path);
let obj = { let obj = {
"temperature": "21°", 'temperature': '21°',
"formImages": { "image": fd } 'formImages': {'image': fd}
}; };
formBindingData.createFormBindingData(obj); let formBindingDataObj = formBindingData.createFormBindingData(obj);
} catch (error.code) { });
console.log('catch error, error:' + JSON.stringify(error));
}
``` ```
# @ohos.application.formHost (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** > **NOTE**
> >
...@@ -34,12 +34,10 @@ Deletes a widget. After this API is called, the application can no longer use th ...@@ -34,12 +34,10 @@ Deletes a widget. After this API is called, the application can no longer use th
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.deleteForm(formId, (error, data) => { formHost.deleteForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost deleteForm, error:' + JSON.stringify(error)); console.log('formHost deleteForm, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -66,16 +64,14 @@ Deletes a widget. After this API is called, the application can no longer use th ...@@ -66,16 +64,14 @@ Deletes a widget. After this API is called, the application can no longer use th
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Parameters** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.deleteForm(formId).then(() => { formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost deleteForm, error:' + JSON.stringify(error)); console.log('formHost deleteForm, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -99,14 +95,10 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -99,14 +95,10 @@ Releases a widget. After this API is called, the application can no longer use t
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.releaseForm(formId, (error, data) => { formHost.releaseForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost releaseForm, error:' + JSON.stringify(error)); console.log('formHost releaseForm, error:' + JSON.stringify(error));
} else {
console.log('formHost releaseForm success');
} }
}); });
``` ```
...@@ -132,14 +124,10 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -132,14 +124,10 @@ Releases a widget. After this API is called, the application can no longer use t
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.releaseForm(formId, true, (error, data) => { formHost.releaseForm(formId, true, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost releaseForm, error:' + JSON.stringify(error)); console.log('formHost releaseForm, error:' + JSON.stringify(error));
} else {
console.log('formHost releaseForm success');
} }
}); });
``` ```
...@@ -170,13 +158,11 @@ Releases a widget. After this API is called, the application can no longer use t ...@@ -170,13 +158,11 @@ Releases a widget. After this API is called, the application can no longer use t
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.releaseForm(formId, true).then(() => { formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success'); console.log('formHost releaseForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost releaseForm, error:' + JSON.stringify(error)); console.log('formHost releaseForm, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -200,12 +186,10 @@ Requests a widget update. This API uses an asynchronous callback to return the r ...@@ -200,12 +186,10 @@ Requests a widget update. This API uses an asynchronous callback to return the r
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.requestForm(formId, (error, data) => { formHost.requestForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost requestForm, error:' + JSON.stringify(error)); console.log('formHost requestForm, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -235,13 +219,11 @@ Requests a widget update. This API uses a promise to return the result. ...@@ -235,13 +219,11 @@ Requests a widget update. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.requestForm(formId).then(() => { formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success'); console.log('formHost requestForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost requestForm, error:' + JSON.stringify(error)); console.log('formHost requestForm, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -265,12 +247,10 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb ...@@ -265,12 +247,10 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.castTempForm(formId, (error, data) => { formHost.castTempForm(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost castTempForm, error:' + JSON.stringify(error)); console.log('formHost castTempForm, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -300,13 +280,11 @@ Converts a temporary widget to a normal one. This API uses a promise to return t ...@@ -300,13 +280,11 @@ Converts a temporary widget to a normal one. This API uses a promise to return t
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.castTempForm(formId).then(() => { formHost.castTempForm(formId).then(() => {
console.log('formHost castTempForm success'); console.log('formHost castTempForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost castTempForm, error:' + JSON.stringify(error)); console.log('formHost castTempForm, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -330,12 +308,10 @@ Instructs the widget framework to make a widget visible. After this API is calle ...@@ -330,12 +308,10 @@ Instructs the widget framework to make a widget visible. After this API is calle
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId, (error, data) => { formHost.notifyVisibleForms(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -365,13 +341,11 @@ Instructs the widget framework to make a widget visible. After this API is calle ...@@ -365,13 +341,11 @@ Instructs the widget framework to make a widget visible. After this API is calle
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId).then(() => { formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success'); console.log('formHost notifyVisibleForms success');
}).catch((error) => { }).catch((error) => {
console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -395,12 +369,10 @@ Instructs the widget framework to make a widget invisible. After this API is cal ...@@ -395,12 +369,10 @@ Instructs the widget framework to make a widget invisible. After this API is cal
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId, (error, data) => { formHost.notifyInvisibleForms(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -430,13 +402,11 @@ Instructs the widget framework to make a widget invisible. After this API is cal ...@@ -430,13 +402,11 @@ Instructs the widget framework to make a widget invisible. After this API is cal
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId).then(() => { formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success'); console.log('formHost notifyInvisibleForms success');
}).catch((error) => { }).catch((error) => {
console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -460,12 +430,10 @@ Instructs the widget framework to make a widget updatable. After this API is cal ...@@ -460,12 +430,10 @@ Instructs the widget framework to make a widget updatable. After this API is cal
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId, (error, data) => { formHost.enableFormsUpdate(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -495,13 +463,11 @@ Instructs the widget framework to make a widget updatable. After this API is cal ...@@ -495,13 +463,11 @@ Instructs the widget framework to make a widget updatable. After this API is cal
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId).then(() => { formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success'); console.log('formHost enableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -525,12 +491,10 @@ Instructs the widget framework to make a widget not updatable. After this API is ...@@ -525,12 +491,10 @@ Instructs the widget framework to make a widget not updatable. After this API is
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId, (error, data) => { formHost.disableFormsUpdate(formId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -560,13 +524,11 @@ Instructs the widget framework to make a widget not updatable. After this API is ...@@ -560,13 +524,11 @@ Instructs the widget framework to make a widget not updatable. After this API is
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = ['12400633174999288'];
let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId).then(() => { formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success'); console.log('formHost disableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -587,12 +549,10 @@ Checks whether the system is ready. This API uses an asynchronous callback to re ...@@ -587,12 +549,10 @@ Checks whether the system is ready. This API uses an asynchronous callback to re
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.isSystemReady((error, data) => { formHost.isSystemReady((error, data) => {
if (error.code) { if (error.code) {
console.error('formHost isSystemReady, error:' + JSON.stringify(error)); console.log('formHost isSystemReady, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -614,13 +574,11 @@ Checks whether the system is ready. This API uses a promise to return the result ...@@ -614,13 +574,11 @@ Checks whether the system is ready. This API uses a promise to return the result
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let formId = "12400633174999288";
formHost.isSystemReady().then(() => { formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success'); console.log('formHost isSystemReady success');
}).catch((error) => { }).catch((error) => {
console.error('formHost isSystemReady, error:' + JSON.stringify(error)); console.log('formHost isSystemReady, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -638,16 +596,14 @@ Obtains the widget information provided by all applications on the device. This ...@@ -638,16 +596,14 @@ Obtains the widget information provided by all applications on the device. This
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| 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.| | 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, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
formHost.getAllFormsInfo((error, data) => { formHost.getAllFormsInfo((error, data) => {
if (error.code) { if (error.code) {
console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data));
} }
...@@ -668,17 +624,15 @@ Obtains the widget information provided by all applications on the device. This ...@@ -668,17 +624,15 @@ Obtains the widget information provided by all applications on the device. This
| Type | Description | | Type | Description |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
formHost.getAllFormsInfo().then((data) => { formHost.getAllFormsInfo().then((data) => {
console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -697,16 +651,14 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -697,16 +651,14 @@ Obtains the widget information provided by a given application on the device. Th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.| | bundleName | string | Yes| Bundle name of the application.|
| 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.| | 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, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => {
formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
...@@ -729,18 +681,16 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -729,18 +681,16 @@ Obtains the widget information provided by a given application on the device. Th
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| bundleName | string | Yes| Bundle name of the application.| | bundleName | string | Yes| Bundle name of the application.|
| moduleName | string | Yes| Module name.| | moduleName | string | Yes| Module name.|
| 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.| | 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, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
``` ```
...@@ -766,17 +716,15 @@ Obtains the widget information provided by a given application on the device. Th ...@@ -766,17 +716,15 @@ Obtains the widget information provided by a given application on the device. Th
| Type | Description | | Type | Description |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](js-apis-application-formInfo.md)&gt;&gt; | Promise used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data) => {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log('formHost getFormsInfo, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -800,12 +748,10 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to ...@@ -800,12 +748,10 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds, (error, data) => { formHost.deleteInvalidForms(formIds, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
} }
...@@ -837,13 +783,11 @@ Deletes invalid widgets from the list. This API uses a promise to return the res ...@@ -837,13 +783,11 @@ Deletes invalid widgets from the list. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds).then((data) => { formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -862,26 +806,24 @@ Obtains the widget state. This API uses an asynchronous callback to return the r ...@@ -862,26 +806,24 @@ Obtains the widget state. This API uses an asynchronous callback to return the r
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| 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.| | 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.| | callback | AsyncCallback&lt;[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** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
let want = { let want = {
"deviceId": "", 'deviceId': '',
"bundleName": "ohos.samples.FormApplication", 'bundleName': 'ohos.samples.FormApplication',
"abilityName": "FormAbility", 'abilityName': 'FormAbility',
"parameters": { 'parameters': {
"ohos.extra.param.key.module_name": "entry", 'ohos.extra.param.key.module_name': 'entry',
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.form_dimension": 2 'ohos.extra.param.key.form_dimension': 2
} }
}; };
formHost.acquireFormState(want, (error, data) => { formHost.acquireFormState(want, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost acquireFormState, error:' + JSON.stringify(error)); console.log('formHost acquireFormState, error:' + JSON.stringify(error));
} else { } else {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
} }
...@@ -913,28 +855,26 @@ Obtains the widget state. This API uses a promise to return the result. ...@@ -913,28 +855,26 @@ Obtains the widget state. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
let want = { let want = {
"deviceId": "", 'deviceId': '',
"bundleName": "ohos.samples.FormApplication", 'bundleName': 'ohos.samples.FormApplication',
"abilityName": "FormAbility", 'abilityName': 'FormAbility',
"parameters": { 'parameters': {
"ohos.extra.param.key.module_name": "entry", 'ohos.extra.param.key.module_name': 'entry',
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.form_dimension": 2 'ohos.extra.param.key.form_dimension': 2
} }
}; };
formHost.acquireFormState(want).then((data) => { formHost.acquireFormState(want).then((data) => {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error('formHost acquireFormState, error:' + JSON.stringify(error)); console.log('formHost acquireFormState, error:' + JSON.stringify(error));
}); });
``` ```
## on("formUninstall") ## on('formUninstall')
on(type: "formUninstall", callback: Callback&lt;string&gt;): void on(type: 'formUninstall', callback: Callback&lt;string&gt;): void
Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result.
...@@ -944,23 +884,21 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to ...@@ -944,23 +884,21 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| | type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.|
| callback | Callback&lt;string&gt; | Yes| Callback used to return the widget ID.| | callback | Callback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
let callback = function(formId) { let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId); console.log('formHost on formUninstall, formId:' + formId);
} }
formHost.on("formUninstall", callback); formHost.on('formUninstall', callback);
``` ```
## off("formUninstall") ## off('formUninstall')
off(type: "formUninstall", callback?: Callback&lt;string&gt;): void off(type: 'formUninstall', callback?: Callback&lt;string&gt;): void
Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result.
...@@ -970,18 +908,16 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac ...@@ -970,18 +908,16 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| | 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.<br> The value must be the same as that in **on("formUninstall")**.| | 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** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost';
let callback = function(formId) { let callback = function(formId) {
console.log('formHost on formUninstall, formId:' + formId); console.log('formHost on formUninstall, formId:' + formId);
} }
formHost.off("formUninstall", callback); formHost.off('formUninstall', callback);
``` ```
## notifyFormsVisible ## notifyFormsVisible
...@@ -1005,12 +941,10 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous ...@@ -1005,12 +941,10 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsVisible(formIds, true, (error, data) => { formHost.notifyFormsVisible(formIds, true, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -1041,13 +975,11 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret ...@@ -1041,13 +975,11 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsVisible(formIds, true).then(() => { formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success'); console.log('formHost notifyFormsVisible success');
}).catch((error) => { }).catch((error) => {
console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -1072,12 +1004,10 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou ...@@ -1072,12 +1004,10 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -1108,13 +1038,11 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r ...@@ -1108,13 +1038,11 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsEnableUpdate(formIds, true).then(() => { formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success'); console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => { }).catch((error) => {
console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error));
}); });
``` ```
## shareForm<sup>9+</sup> ## shareForm<sup>9+</sup>
...@@ -1123,7 +1051,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;) ...@@ -1123,7 +1051,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. Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC **Required permissions**: ohos.permission.REQUIRE_FORM
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -1138,13 +1066,11 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca ...@@ -1138,13 +1066,11 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca
**Example** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
formHost.shareForm(formId, deviceId, (error, data) => { formHost.shareForm(formId, deviceId, (error, data) => {
if (error.code) { if (error.code) {
console.error('formHost shareForm, error:' + JSON.stringify(error)); console.log('formHost shareForm, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -1172,23 +1098,21 @@ Shares a specified widget with a remote device. This API uses a promise to retur ...@@ -1172,23 +1098,21 @@ Shares a specified widget with a remote device. This API uses a promise to retur
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Parameters** **Example**
```ts ```ts
import formHost from '@ohos.application.formHost'; let formId = '12400633174999288';
let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2';
let formId = "12400633174999288";
let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
formHost.shareForm(formId, deviceId).then(() => { formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost shareForm, error:' + JSON.stringify(error)); console.log('formHost shareForm, error:' + JSON.stringify(error));
}); });
``` ```
## notifyFormsPrivacyProtected<sup>9+</sup> ## notifyFormsPrivacyProtected<sup>9+</sup>
notifyFormsPrivacyProtected(formIds: Array&lt;string&gt;, isProtected: boolean, callback: AsyncCallback&lt;void&gt;): void 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. Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result.
...@@ -1204,51 +1128,10 @@ Notifies that the privacy protection status of the specified widgets changes. Th ...@@ -1204,51 +1128,10 @@ Notifies that the privacy protection status of the specified widgets changes. Th
| deviceId | string | Yes | Remote device ID.| | deviceId | string | Yes | Remote device ID.|
```ts ```ts
import formHost from '@ohos.application.formHost'; let formIds = new Array('12400633174999288', '12400633174999289');
let formIds = new Array("12400633174999288", "12400633174999289");
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
console.error('formHost shareForm, error:' + JSON.stringify(error)); console.log('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.formProvider (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. 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** > **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 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 ## Modules to Import
...@@ -31,13 +31,11 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback ...@@ -31,13 +31,11 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288';
let formId = "12400633174999288";
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -65,13 +63,11 @@ Sets the next refresh time for a widget. This API uses a promise to return the r ...@@ -65,13 +63,11 @@ Sets the next refresh time for a widget. This API uses a promise to return the r
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288';
let formId = "12400633174999288";
formProvider.setFormNextRefreshTime(formId, 5).then(() => { formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log('formProvider setFormNextRefreshTime success'); console.log('formProvider setFormNextRefreshTime success');
}).catch((error) => { }).catch((error) => {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -88,21 +84,19 @@ Updates a widget. This API uses an asynchronous callback to return the result. ...@@ -88,21 +84,19 @@ Updates a widget. This API uses an asynchronous callback to return the result.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.| | 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.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288';
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj, (error, data) => { formProvider.updateForm(formId, obj, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider updateForm, error:' + JSON.stringify(error)); console.log('formProvider updateForm, error:' + JSON.stringify(error));
} }
}); });
``` ```
...@@ -119,7 +113,7 @@ Updates a widget. This API uses a promise to return the result. ...@@ -119,7 +113,7 @@ Updates a widget. This API uses a promise to return the result.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| formId | string | Yes | ID of the widget to update.| | 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#formbindingdat) | Yes | Data to be used for the update. |
**Return value** **Return value**
...@@ -131,14 +125,12 @@ Updates a widget. This API uses a promise to return the result. ...@@ -131,14 +125,12 @@ Updates a widget. This API uses a promise to return the result.
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; let formId = '12400633174999288';
let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj).then(() => { formProvider.updateForm(formId, obj).then(() => {
console.log('formProvider updateForm success'); console.log('formProvider updateForm success');
}).catch((error) => { }).catch((error) => {
console.log('formProvider updateForm, error:' + JSON.stringify(error)); console.log('formProvider updateForm, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -154,19 +146,17 @@ Obtains the application's widget information on the device. This API uses an asy ...@@ -154,19 +146,17 @@ Obtains the application's widget information on the device. This API uses an asy
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
formProvider.getFormsInfo((error, data) => { formProvider.getFormsInfo((error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
``` ```
## getFormsInfo<sup>9+</sup> ## getFormsInfo<sup>9+</sup>
...@@ -182,24 +172,22 @@ Obtains the application's widget information that meets a filter criterion on th ...@@ -182,24 +172,22 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| | filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formInfo from '@ohos.application.formInfo'; import formInfo from '@ohos.application.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter : formInfo.FormInfoFilter = { const filter : formInfo.FormInfoFilter = {
// get info of forms belong to module entry. // get info of forms belong to module entry.
moduleName : "entry" moduleName : 'entry'
}; };
formProvider.getFormsInfo(filter, (error, data) => { formProvider.getFormsInfo(filter, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
} else { } else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
``` ```
...@@ -221,22 +209,20 @@ Obtains the application's widget information on the device. This API uses a prom ...@@ -221,22 +209,20 @@ Obtains the application's widget information on the device. This API uses a prom
| Type | Description | | Type | Description |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Promise used to return the information obtained.| | Promise&lt;Array&lt;[FormInfo](./js-apis-application-formInfo.md#forminfo-1)&gt;&gt; | Promise used to return the information obtained.|
**Example** **Example**
```ts ```ts
import formInfo from '@ohos.application.formInfo'; import formInfo from '@ohos.application.formInfo';
import formProvider from '@ohos.app.form.formProvider';
const filter : formInfo.FormInfoFilter = { const filter : formInfo.FormInfoFilter = {
// get info of forms belong to module entry. // get info of forms belong to module entry.
moduleName : "entry" moduleName : 'entry'
}; };
formProvider.getFormsInfo(filter).then((data) => { formProvider.getFormsInfo(filter).then((data) => {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log('formProvider getFormsInfo, error:' + JSON.stringify(error));
}); });
``` ```
...@@ -255,29 +241,28 @@ Requests to publish a widget carrying data to the widget host. This API uses an ...@@ -255,29 +241,28 @@ Requests to publish a widget carrying data to the widget host. This API uses an
| Name| Type | Mandatory| Description | | 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" | | 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.| | callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the widget ID.|
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
let want = { let want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'});
formProvider.requestPublishForm(want, obj, (error, data) => { formProvider.requestPublishForm(want, obj, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
``` ```
...@@ -301,22 +286,20 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c ...@@ -301,22 +286,20 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
let want = { let want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
formProvider.requestPublishForm(want, (error, data) => { formProvider.requestPublishForm(want, (error, data) => {
if (error.code) { if (error.code) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
``` ```
...@@ -335,7 +318,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu ...@@ -335,7 +318,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
| Name | Type | Mandatory| Description | | 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" | | 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.|
**Return value** **Return value**
...@@ -346,20 +329,18 @@ Requests to publish a widget to the widget host. This API uses a promise to retu ...@@ -346,20 +329,18 @@ Requests to publish a widget to the widget host. This API uses a promise to retu
**Example** **Example**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
let want = { let want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error));
}); });
``` ```
...@@ -388,12 +369,12 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { ...@@ -388,12 +369,12 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => {
} else { } else {
if (isSupported) { if (isSupported) {
let want = { let want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
formProvider.requestPublishForm(want, (error, data) => { formProvider.requestPublishForm(want, (error, data) => {
if (error.code) { if (error.code) {
...@@ -429,12 +410,12 @@ Checks whether a widget can be published to the widget host. This API uses a pro ...@@ -429,12 +410,12 @@ Checks whether a widget can be published to the widget host. This API uses a pro
formProvider.isRequestPublishFormSupported().then((isSupported) => { formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) { if (isSupported) {
let want = { let want = {
abilityName: "FormAbility", abilityName: 'FormAbility',
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, 'ohos.extra.param.key.form_dimension': 2,
"ohos.extra.param.key.form_name": "widget", 'ohos.extra.param.key.form_name': 'widget',
"ohos.extra.param.key.module_name": "entry" 'ohos.extra.param.key.module_name': 'entry'
} }
}; };
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
...@@ -445,4 +426,4 @@ formProvider.isRequestPublishFormSupported().then((isSupported) => { ...@@ -445,4 +426,4 @@ formProvider.isRequestPublishFormSupported().then((isSupported) => {
}).catch((error) => { }).catch((error) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error));
}); });
``` ```
\ No newline at end of file
...@@ -4,12 +4,12 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions, ...@@ -4,12 +4,12 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions,
> **NOTE** > **NOTE**
> >
> 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. > The 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 ## Modules to Import
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
``` ```
## Required Permissions ## Required Permissions
...@@ -43,17 +43,17 @@ Registers a listener to observe the mission status. ...@@ -43,17 +43,17 @@ Registers a listener to observe the mission status.
**Example** **Example**
```ts ```ts
var listener = { let listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, 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-------")} onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');}
}; };
console.log("registerMissionListener") console.log('registerMissionListener');
var listenerid = missionManager.registerMissionListener(listener); let listenerid = missionManager.registerMissionListener(listener);
``` ```
...@@ -79,21 +79,21 @@ Deregisters a mission status listener. This API uses an asynchronous callback to ...@@ -79,21 +79,21 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
var listener = { let listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, 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-------")} onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');}
}; };
console.log("registerMissionListener") console.log('registerMissionListener');
var listenerid = missionManager.registerMissionListener(listener); let listenerid = missionManager.registerMissionListener(listener);
missionManager.unregisterMissionListener(listenerid, (error) => { missionManager.unregisterMissionListener(listenerid, (error) => {
console.log("unregisterMissionListener"); console.log('unregisterMissionListener');
}) });
``` ```
...@@ -124,17 +124,17 @@ Deregisters a mission status listener. This API uses a promise to return the res ...@@ -124,17 +124,17 @@ Deregisters a mission status listener. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
var listener = { let listener = {
onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');},
onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');},
onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');},
onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');},
onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, 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-------")} onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');}
}; };
console.log("registerMissionListener") console.log('registerMissionListener');
var listenerid = missionManager.registerMissionListener(listener); let listenerid = missionManager.registerMissionListener(listener);
missionManager.unregisterMissionListener(listenerid).catch(function (err) { missionManager.unregisterMissionListener(listenerid).catch(function (err) {
console.log(err); console.log(err);
...@@ -167,20 +167,15 @@ Obtains the information about a given mission. This API uses an asynchronous cal ...@@ -167,20 +167,15 @@ Obtains the information about a given mission. This API uses an asynchronous cal
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager'
var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);});
missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { missionManager.getMissionInfo('', allMissions[0].missionId, (error, mission) => {
if (error.code) { console.log('getMissionInfo is called, error.code = ' + error.code)
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + console.log('mission.missionId = ' + mission.missionId);
"error.message:" + JSON.stringify(error.message)); console.log('mission.runningState = ' + mission.runningState);
return; console.log('mission.lockedState = ' + mission.lockedState);
} console.log('mission.timestamp = ' + mission.timestamp);
console.log('mission.label = ' + mission.label);
console.log("mission.missionId = " + mission.missionId); console.log('mission.iconPath = ' + mission.iconPath);
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);
}); });
``` ```
...@@ -213,9 +208,9 @@ Obtains the information about a given mission. This API uses a promise to return ...@@ -213,9 +208,9 @@ Obtains the information about a given mission. This API uses a promise to return
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var mission = missionManager.getMissionInfo("", 10).catch(function (err){ let mission = missionManager.getMissionInfo('', 10).catch(function (err){
console.log(err); console.log(err);
}); });
``` ```
...@@ -244,17 +239,13 @@ Obtains information about all missions. This API uses an asynchronous callback t ...@@ -244,17 +239,13 @@ Obtains information about all missions. This API uses an asynchronous callback t
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; });
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
})
``` ```
...@@ -286,9 +277,9 @@ Obtains information about all missions. This API uses a promise to return the re ...@@ -286,9 +277,9 @@ Obtains information about all missions. This API uses a promise to return the re
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){
console.log(err); console.log(err);
}); });
``` ```
...@@ -317,27 +308,19 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback ...@@ -317,27 +308,19 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
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));
let id = missions[0].missionId;
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionSnapShot('', id, (error, snapshot) => {
if (error.code) { console.log('getMissionSnapShot is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('bundleName = ' + snapshot.ability.bundleName);
"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) => {
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);
})
})
``` ```
...@@ -369,17 +352,17 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r ...@@ -369,17 +352,17 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ let snapshot = missionManager.getMissionSnapShot('', id).catch(function (err){
console.log(err); console.log(err);
}); });
``` ```
...@@ -407,27 +390,19 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr ...@@ -407,27 +390,19 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
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));
let id = missions[0].missionId;
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => {
if (error.code) { console.log('getLowResolutionMissionSnapShot is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('bundleName = ' + snapshot.ability.bundleName);
"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) => {
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);
})
})
``` ```
...@@ -459,17 +434,17 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise ...@@ -459,17 +434,17 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (err){
console.log(err); console.log(err);
}); });
``` ```
...@@ -497,20 +472,16 @@ Locks a given mission. This API uses an asynchronous callback to return the resu ...@@ -497,20 +472,16 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; let id = missions[0].missionId;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.lockMission(id).then(() => { missionManager.lockMission(id).then(() => {
console.log("lockMission is called "); console.log('lockMission is called ');
}); });
}); });
``` ```
...@@ -543,14 +514,14 @@ Locks a given mission. This API uses a promise to return the result. ...@@ -543,14 +514,14 @@ Locks a given mission. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){ missionManager.lockMission(id).catch(function (err){
console.log(err); console.log(err);
...@@ -580,20 +551,16 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re ...@@ -580,20 +551,16 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; let id = missions[0].missionId;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.unlockMission(id).then(() => { missionManager.unlockMission(id).then(() => {
console.log("unlockMission is called "); console.log('unlockMission is called ');
}); });
}); });
``` ```
...@@ -626,15 +593,15 @@ Unlocks a given mission. This API uses a promise to return the result. ...@@ -626,15 +593,15 @@ Unlocks a given mission. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
missionManager.lockMission(id).catch(function (err){ missionManager.lockMission(id).catch(function (err){
console.log(err); console.log(err);
...@@ -667,20 +634,16 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy ...@@ -667,20 +634,16 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; let id = missions[0].missionId;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.clearMission(id).then(() => { missionManager.clearMission(id).then(() => {
console.log("clearMission is called "); console.log('clearMission is called ');
}); });
}); });
``` ```
...@@ -713,15 +676,15 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom ...@@ -713,15 +676,15 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
missionManager.clearMission(id).catch(function (err){ missionManager.clearMission(id).catch(function (err){
console.log(err); console.log(err);
...@@ -744,10 +707,10 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t ...@@ -744,10 +707,10 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.clearAllMissions().then(() => { missionManager.clearAllMissions().then(() => {
console.log("clearAllMissions is called "); console.log('clearAllMissions is called ');
}); });
``` ```
...@@ -773,7 +736,7 @@ Clears all unlocked missions. This API uses a promise to return the result. ...@@ -773,7 +736,7 @@ Clears all unlocked missions. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.clearAllMissions().catch(function (err){ missionManager.clearAllMissions().catch(function (err){
console.log(err); console.log(err);
}); });
...@@ -802,20 +765,16 @@ Switches a given mission to the foreground. This API uses an asynchronous callba ...@@ -802,20 +765,16 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; let id = missions[0].missionId;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.moveMissionToFront(id).then(() => { missionManager.moveMissionToFront(id).then(() => {
console.log("moveMissionToFront is called "); console.log('moveMissionToFront is called ');
}); });
}); });
``` ```
...@@ -838,26 +797,22 @@ Switches a given mission to the foreground, with the startup parameters for the ...@@ -838,26 +797,22 @@ Switches a given mission to the foreground, with the startup parameters for the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| missionId | number | Yes| Mission ID.| | missionId | number | Yes| Mission ID.|
| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
missionManager.getMissionInfos("", 10, (error, missions) => { missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) { console.log('getMissionInfos is called, error.code = ' + error.code);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('size = ' + missions.length);
"error.message:" + JSON.stringify(error.message)); console.log('missions = ' + JSON.stringify(missions));
return; let id = missions[0].missionId;
}
console.log("size = " + missions.length);
console.log("missions = " + JSON.stringify(missions));
var id = missions[0].missionId;
missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => {
console.log("moveMissionToFront is called "); console.log('moveMissionToFront is called ');
}); });
}); });
``` ```
...@@ -880,7 +835,7 @@ Switches a given mission to the foreground, with the startup parameters for the ...@@ -880,7 +835,7 @@ Switches a given mission to the foreground, with the startup parameters for the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| missionId | number | Yes| Mission ID.| | missionId | number | Yes| Mission ID.|
| options | [StartOptions](js-apis-application-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
**Return value** **Return value**
...@@ -891,15 +846,15 @@ Switches a given mission to the foreground, with the startup parameters for the ...@@ -891,15 +846,15 @@ Switches a given mission to the foreground, with the startup parameters for the
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.application.missionManager' import missionManager from '@ohos.application.missionManager';
var allMissions; let allMissions;
missionManager.getMissionInfos("",10).then(function(res){ missionManager.getMissionInfos('',10).then(function(res){
allMissions=res; allMissions=res;
}).catch(function(err){console.log(err);}); }).catch(function(err){console.log(err);});
console.log("size = " + allMissions.length); console.log('size = ' + allMissions.length);
console.log("missions = " + JSON.stringify(allMissions)); console.log('missions = ' + JSON.stringify(allMissions));
var id = allMissions[0].missionId; let id = allMissions[0].missionId;
missionManager.moveMissionToFront(id).catch(function (err){ missionManager.moveMissionToFront(id).catch(function (err){
console.log(err); console.log(err);
......
...@@ -10,7 +10,7 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for ...@@ -10,7 +10,7 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for
## Modules to Import ## Modules to Import
```ts ```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility';
``` ```
## StaticSubscriberExtensionAbility.onReceiveEvent ## StaticSubscriberExtensionAbility.onReceiveEvent
...@@ -27,17 +27,14 @@ Callback of the common event of a static subscriber. ...@@ -27,17 +27,14 @@ Callback of the common event of a static subscriber.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.| | event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.|
**Example** **Example**
```ts ```ts
var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility {
{ onReceiveEvent(event) {
onReceiveEvent(event){ console.log('onReceiveEvent, event: ' + JSON.stringify(event));
console.log('onReceiveEvent,event:' + event.code); }
} }
}
export default MyStaticSubscriberExtensionAbility
``` ```
...@@ -11,7 +11,7 @@ To implement your own unit test framework, extend this class and override its AP ...@@ -11,7 +11,7 @@ To implement your own unit test framework, extend this class and override its AP
## Modules to Import ## Modules to Import
```ts ```ts
import TestRunner from '@ohos.application.testRunner' import TestRunner from '@ohos.application.testRunner';
``` ```
## TestRunner.onPrepare ## TestRunner.onPrepare
...@@ -27,7 +27,7 @@ Prepares the unit test environment to run test cases. ...@@ -27,7 +27,7 @@ Prepares the unit test environment to run test cases.
```ts ```ts
export default class UserTestRunner implements TestRunner { export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onPrepare") console.log('Trigger onPrepare');
} }
onRun() {} onRun() {}
}; };
...@@ -49,7 +49,7 @@ Runs test cases. ...@@ -49,7 +49,7 @@ Runs test cases.
export default class UserTestRunner implements TestRunner { export default class UserTestRunner implements TestRunner {
onPrepare() {} onPrepare() {}
onRun() { onRun() {
console.log("Trigger onRun") console.log('Trigger onRun');
} }
}; };
``` ```
...@@ -4,7 +4,7 @@ Want is a carrier for information transfer between objects (application componen ...@@ -4,7 +4,7 @@ Want is a carrier for information transfer between objects (application componen
> **NOTE** > **NOTE**
> >
> 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. > 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.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 ## Modules to Import
...@@ -18,119 +18,117 @@ import Want from '@ohos.application.Want'; ...@@ -18,119 +18,117 @@ import Want from '@ohos.application.Want';
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | | deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name.| | bundleName | string | No | Bundle name. If both **bundleName** and **abilityName** are specified in a bWantb, the **Want** can directly match the specified ability.|
| 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.| | 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**.| | 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. | | 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).| | 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. 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). | | 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. |
| 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. | | 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.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files. |
| 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). | | 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. |
| moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.| | moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.|
**Example** **Example**
- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). - Basic usage
```ts ```ts
let want = { let want = {
"deviceId": "", // An empty deviceId indicates the local device. 'deviceId': '', // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication", 'bundleName': 'com.extreme.test',
"abilityName": "EntryAbility", 'abilityName': 'MainAbility',
"moduleName": "entry" // moduleName is optional. 'moduleName': 'entry' // moduleName is optional.
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code)
}) });
``` ```
- 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): - Data is transferred through user-defined fields. The following data types are supported:
* String * String
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "EntryAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForString: "str", keyForString: 'str',
}, },
} };
``` ```
* Number * Number
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "EntryAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForInt: 100, keyForInt: 100,
keyForDouble: 99.99, keyForDouble: 99.99,
}, },
} };
``` ```
* Boolean * Boolean
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "EntryAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForBool: true, keyForBool: true,
}, },
} };
``` ```
* Object * Object
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "EntryAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForObject: { keyForObject: {
keyForObjectString: "str", keyForObjectString: 'str',
keyForObjectInt: -200, keyForObjectInt: -200,
keyForObjectDouble: 35.5, keyForObjectDouble: 35.5,
keyForObjectBool: false, keyForObjectBool: false,
}, },
}, },
} };
``` ```
* Array * Array
```ts ```ts
let want = { let want = {
bundleName: "com.example.myapplication", bundleName: 'com.example.demo',
abilityName: "EntryAbility", abilityName: 'com.example.demo.MainAbility',
parameters: { parameters: {
keyForArrayString: ["str1", "str2", "str3"], keyForArrayString: ['str1', 'str2', 'str3'],
keyForArrayInt: [100, 200, 300, 400], keyForArrayInt: [100, 200, 300, 400],
keyForArrayDouble: [0.1, 0.2], keyForArrayDouble: [0.1, 0.2],
keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], keyForArrayObject: [{obj1: 'aaa'}, {obj2: 100}],
}, },
} };
``` ```
* File descriptor (FD) * File descriptor (FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync('/data/storage/el2/base/haps/pic.png');
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(e)); console.log('openSync fail:' + JSON.stringify(e));
} }
let want = { let want = {
"deviceId": "", // An empty deviceId indicates the local device. 'deviceId': '', // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication", 'bundleName': 'com.extreme.test',
"abilityName": "EntryAbility", 'abilityName': 'MainAbility',
"moduleName": "entry", // moduleName is optional. 'moduleName': 'entry', // moduleName is optional.
"parameters": { 'parameters': {
"keyFd":{"type":"FD", "value":fd} 'keyFd':{'type':'FD', 'value':fd}
} }
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code)
}) });
``` ```
- For more details and examples, see [Want](../../application-models/want-overview.md).
<!--no_check--> <!--no_check-->
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> The APIs provided by this module are system APIs. > The APIs provided by this module are system APIs.
> >
> The APIs of this module can be used only in the stage model. > The APIs of this module can be used only in the stage model.
...@@ -22,7 +22,7 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; ...@@ -22,7 +22,7 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------------------- | | --------- | -------- | ---- | ---- | ------------------------- |
| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes | No | Context of an Extension ability. | | context | [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md) | Yes | No | Context of an Extension ability. |
## WindowExtensionAbility.onConnect ## WindowExtensionAbility.onConnect
...@@ -101,9 +101,9 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -101,9 +101,9 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
window.loadContent('WindowExtAbility/pages/index1').then(() => { window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => { window.getProperties().then((pro) => {
console.log('WindowExtension ' + JSON.stringify(pro)); console.log('WindowExtension ' + JSON.stringify(pro));
}) });
window.show(); window.show();
}) });
} }
} }
......
# ConnectOptions # ConnectOptions
**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. **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-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) to connect to a ServiceExtensionAbility.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -9,3 +9,26 @@ ...@@ -9,3 +9,26 @@
| onConnect<sup>7+</sup> | function | Yes | Callback invoked when a connection is set up. | | 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. | | 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.| | onFailed<sup>7+</sup> | function | Yes | Callback invoked when a connection fails.|
**Example**
```ts
let want = {
bundleName: 'com.example.myapp',
abilityName: 'MyAbility'
};
let connectOptions = {
onConnect(elementName, remote) {
console.log('onConnect elementName: ' + elementName);
},
onDisconnect(elementName) {
console.log('onDisconnect elementName: ' + elementName);
},
onFailed(code) {
console.error('onFailed code: ' + code);
}
};
let connection = this.context.connectAbility(want, connectOptions);
```
...@@ -35,12 +35,12 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret ...@@ -35,12 +35,12 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var mode = "rw"; let mode = 'rwt';
DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { DAHelper.openFile('dataability:///com.example.DataAbility', mode, (err) => {
console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -69,12 +69,12 @@ Opens a file with a specified URI. This API uses a promise to return a file desc ...@@ -69,12 +69,12 @@ Opens a file with a specified URI. This API uses a promise to return a file desc
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var mode = "rw"; let mode = 'rwt';
DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { DAHelper.openFile('dataability:///com.example.DataAbility', mode).then((data) => {
console.info("openFile data: " + JSON.stringify(data)); console.info('==========================>openFileCallback=======================>');
}); });
``` ```
...@@ -98,15 +98,15 @@ Registers an observer to listen for changes in the data specified by a given URI ...@@ -98,15 +98,15 @@ Registers an observer to listen for changes in the data specified by a given URI
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let helper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
function onChangeNotify() { function onChangeNotify() {
console.info("onChangeNotify call back"); console.info('==========================>onChangeNotify=======================>');
}; };
DAHelper.on( helper.on(
"dataChange", 'dataChange',
"dataability:///com.example.DataAbility", 'dataability:///com.example.DataAbility',
onChangeNotify onChangeNotify
); );
``` ```
...@@ -131,20 +131,20 @@ Deregisters the observer that listens for changes in the data specified by a giv ...@@ -131,20 +131,20 @@ Deregisters the observer that listens for changes in the data specified by a giv
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let helper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
function onChangeNotify() { function onChangeNotify() {
console.info("onChangeNotify call back"); console.info('==========================>onChangeNotify=======================>');
}; };
DAHelper.off( helper.off(
"dataChange", 'dataChange',
"dataability:///com.example.DataAbility", 'dataability:///com.example.DataAbility',
onChangeNotify
); );
DAHelper.off( helper.off(
"dataChange", 'dataChange',
"dataability:///com.example.DataAbility", 'dataability:///com.example.DataAbility',
onChangeNotify
); );
``` ```
...@@ -167,11 +167,11 @@ Obtains the media resource type of the data specified by a given URI. This API u ...@@ -167,11 +167,11 @@ Obtains the media resource type of the data specified by a given URI. This API u
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { DAHelper.getType('dataability:///com.example.DataAbility', (err, data) => {
console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -199,11 +199,11 @@ Obtains the media resource type of the data specified by a given URI. This API u ...@@ -199,11 +199,11 @@ Obtains the media resource type of the data specified by a given URI. This API u
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { DAHelper.getType('dataability:///com.example.DataAbility').then((data) => {
console.info("getType data: " + JSON.stringify(data)); console.info('==========================>getTypeCallback=======================>');
}); });
``` ```
...@@ -227,14 +227,17 @@ Obtains the supported media resource types of a specified file. This API uses an ...@@ -227,14 +227,17 @@ Obtains the supported media resource types of a specified file. This API uses an
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { DAHelper.getFileTypes( 'dataability:///com.example.DataAbility',
console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); 'image/*', (err, data) => {
console.info('==========================>Called=======================>');
}); });
``` ```
## DataAbilityHelper.getFileTypes ## DataAbilityHelper.getFileTypes
getFileTypes(uri: string, mimeTypeFilter: string): Promise\<Array\<string>> getFileTypes(uri: string, mimeTypeFilter: string): Promise\<Array\<string>>
...@@ -260,11 +263,12 @@ Obtains the supported media resource types of a specified file. This API uses a ...@@ -260,11 +263,12 @@ Obtains the supported media resource types of a specified file. This API uses a
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { DAHelper.getFileTypes('dataability:///com.example.DataAbility',
console.info("getFileTypes data: " + JSON.stringify(data)); 'image/*').then((data) => {
console.info('===================>getFileTypesCallback================>');
}); });
``` ```
...@@ -287,11 +291,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u ...@@ -287,11 +291,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { DAHelper.normalizeUri('dataability:///com.example.DataAbility', (err, data) => {
console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -319,11 +323,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u ...@@ -319,11 +323,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { DAHelper.normalizeUri('dataability:///com.example.DataAbility',).then((data) => {
console.info("normalizeUri data: " + JSON.stringify(data)); console.info('=================>normalizeUriCallback=======================>');
}); });
``` ```
...@@ -346,14 +350,16 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ...@@ -346,14 +350,16 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (err, data) => {
console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
## DataAbilityHelper.denormalizeUri ## DataAbilityHelper.denormalizeUri
denormalizeUri(uri: string): Promise\<string> denormalizeUri(uri: string): Promise\<string>
...@@ -378,11 +384,11 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ...@@ -378,11 +384,11 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { DAHelper.denormalizeUri('dataability:///com.example.DataAbility',).then((data) => {
console.info("denormalizeUri data: " + JSON.stringify(data)); console.info('===============>denormalizeUriCallback=======================>');
}); });
``` ```
...@@ -405,11 +411,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ...@@ -405,11 +411,11 @@ Notifies the registered observer of a change to the data specified by the URI. T
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let helper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { helper.notifyChange('dataability:///com.example.DataAbility', (err) => {
console.info("==========================>Called=======================>"); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -437,11 +443,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ...@@ -437,11 +443,11 @@ Notifies the registered observer of a change to the data specified by the URI. T
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => {
console.info("================>notifyChangeCallback================>"); console.info('================>notifyChangeCallback================>');
}); });
``` ```
...@@ -465,17 +471,18 @@ Inserts a single data record into the database. This API uses an asynchronous ca ...@@ -465,17 +471,18 @@ Inserts a single data record into the database. This API uses an asynchronous ca
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
const valueBucket = { const valueBucket = {
"name": "rose", 'name': 'rose',
"age": 22, 'age': 22,
"salary": 200.5, 'salary': 200.5,
"blobType": "u8", 'blobType': 'u8',
}; };
DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { DAHelper.insert('dataability:///com.example.DataAbility', valueBucket,
console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); (err, data) => {
console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -504,17 +511,17 @@ Inserts a single data record into the database. This API uses a promise to retur ...@@ -504,17 +511,17 @@ Inserts a single data record into the database. This API uses a promise to retur
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
const valueBucket = { const valueBucket = {
"name": "rose1", 'name': 'rose1',
"age": 221, 'age': 221,
"salary": 20.5, 'salary': 20.5,
"blobType": "u8", 'blobType': 'u8',
}; };
DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { DAHelper.insert('dataability:///com.example.DataAbility', valueBucket).then((data) => {
console.info("insert data: " + JSON.stringify(data)); console.info('====================>insertCallback=======================>');
}); });
``` ```
...@@ -538,14 +545,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c ...@@ -538,14 +545,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',},
{"name": "roe12", "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",}); {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',});
DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { DAHelper.batchInsert('dataability:///com.example.DataAbility', cars,
console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); (err, data) => {
console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -574,14 +582,14 @@ Inserts multiple data records into the database. This API uses a promise to retu ...@@ -574,14 +582,14 @@ Inserts multiple data records into the database. This API uses a promise to retu
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',},
{"name": "roe12", "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",}); {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',});
DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => { DAHelper.batchInsert('dataability:///com.example.DataAbility', cars).then((data) => {
console.info("batchInsert data: " + JSON.stringify(data)); console.info('==================>batchInsertCallback=======================>');
}); });
``` ```
...@@ -606,12 +614,13 @@ Deletes one or more data records from the database. This API uses an asynchronou ...@@ -606,12 +614,13 @@ Deletes one or more data records from the database. This API uses an asynchronou
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => { DAHelper.delete('dataability:///com.example.DataAbility', da,
console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); (err, data) => {
console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -641,12 +650,12 @@ Deletes one or more data records from the database. This API uses a promise to r ...@@ -641,12 +650,12 @@ Deletes one or more data records from the database. This API uses a promise to r
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { DAHelper.delete('dataability:///com.example.DataAbility', da).then((data) => {
console.info("delete data: " + JSON.stringify(data)); console.info('==========================>deleteCallback=======================>');
}); });
``` ```
...@@ -672,18 +681,18 @@ Updates data records in the database. This API uses an asynchronous callback to ...@@ -672,18 +681,18 @@ Updates data records in the database. This API uses an asynchronous callback to
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
const va = { const va = {
"name": "roe1", 'name': 'roe1',
"age": 21, 'age': 21,
"salary": 20.5, 'salary': 20.5,
"blobType": "u8", 'blobType': 'u8',
}; };
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => { DAHelper.update('dataability:///com.example.DataAbility', va, da, (err, data) => {
console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -714,18 +723,18 @@ Updates data records in the database. This API uses a promise to return the resu ...@@ -714,18 +723,18 @@ Updates data records in the database. This API uses a promise to return the resu
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
const va = { const va = {
"name": "roe1", 'name': 'roe1',
"age": 21, 'age': 21,
"salary": 20.5, 'salary': 20.5,
"blobType": "u8", 'blobType': 'u8',
}; };
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { DAHelper.update('dataability:///com.example.DataAbility', va, da).then((data) => {
console.info("update data: " + JSON.stringify(data)); console.info('==========================>updateCallback=======================>');
}); });
``` ```
...@@ -751,13 +760,13 @@ Queries data in the database. This API uses an asynchronous callback to return t ...@@ -751,13 +760,13 @@ Queries data in the database. This API uses an asynchronous callback to return t
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var cars=new Array("value1", "value2", "value3", "value4"); let cars=new Array('value1', 'value2', 'value3', 'value4');
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { DAHelper.query('dataability:///com.example.DataAbility', cars, da, (err, data) => {
console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('==========================>Called=======================>');
}); });
``` ```
...@@ -790,21 +799,21 @@ Queries data in the database. This API uses a promise to return the result. ...@@ -790,21 +799,21 @@ Queries data in the database. This API uses a promise to return the result.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
var DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" 'dataability:///com.example.DataAbility'
); );
var cars = new Array("value1", "value2", "value3", "value4"); let cars = new Array('value1', 'value2', 'value3', 'value4');
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { DAHelper.query('dataability:///com.example.DataAbility', cars, da).then((data) => {
console.info("query data: " + JSON.stringify(data)); console.info('==========================>queryCallback=======================>');
}); });
``` ```
## DataAbilityHelper.call ## 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 an extended API of the DataAbility. 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 **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
...@@ -812,11 +821,16 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback ...@@ -812,11 +821,16 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | --------------------------------- | ---- | ------------------------------------------------ | | ---------- | --------------------------------- | ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the DataAbility. 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. | | method | string | Yes | Name of the API to call. |
| arg | string | Yes | Parameter to pass in. | | arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | | 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** **Example**
...@@ -824,23 +838,20 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback ...@@ -824,23 +838,20 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility" 'dataability:///com.example.jsapidemo.UserDataAbility');
); dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility',
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", 'method', 'arg', {'key1':'value1'}).then((data) => {
"method", "arg", {"key1":"value1"}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + err);
return;
}
console.info('Operation succeeded: ' + data); console.info('Operation succeeded: ' + data);
}).catch((error) => {
console.error('Operation failed. Cause: ' + error);
}); });
``` ```
## DataAbilityHelper.call ## 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 an extended API of the DataAbility. 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 **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
...@@ -848,16 +859,11 @@ Calls an extended API of the DataAbility. This API uses a promise to return the ...@@ -848,16 +859,11 @@ Calls an extended API of the DataAbility. This API uses a promise to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | --------------------------------- | ---- | ------------------------------------------------ | | ---------- | --------------------------------- | ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the DataAbility. 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. | | method | string | Yes | Name of the API to call. |
| arg | string | Yes | Parameter to pass in. | | arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | | 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** **Example**
...@@ -865,13 +871,14 @@ Calls an extended API of the DataAbility. This API uses a promise to return the ...@@ -865,13 +871,14 @@ Calls an extended API of the DataAbility. This API uses a promise to return the
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility" 'dataability:///com.example.jsapidemo.UserDataAbility');
); dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility',
dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", 'method', 'arg', {'key1':'value1'}, (err, data) => {
"method", "arg", {"key1":"value1"}).then((data) => { if (err) {
console.error('Operation failed. Cause: ' + err);
return;
}
console.info('Operation succeeded: ' + data); console.info('Operation succeeded: ' + data);
}).catch((error) => {
console.error('Operation failed. Cause: ' + error);
}); });
``` ```
...@@ -887,7 +894,7 @@ Operates data in the database in batches. This API uses an asynchronous callback ...@@ -887,7 +894,7 @@ Operates data in the database in batches. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------| ---------------------------------| ---- | ------------------------------------------------ | | ----------| ---------------------------------| ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| | 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. | | 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. | | callback | AsyncCallback\<Array\<[DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md)>> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. |
...@@ -899,9 +906,9 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -899,9 +906,9 @@ import featureAbility from '@ohos.ability.featureAbility';
// Select the operations to be performed on the database according to the DataAbilityOperation array. // Select the operations to be performed on the database according to the DataAbilityOperation array.
let op=new Array(); let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility" 'dataability:///com.example.jsapidemo.UserDataAbility');
); dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility',
dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { op, (err, data) => {
if (err) { if (err) {
console.error('Operation failed. Cause: ' + err); console.error('Operation failed. Cause: ' + err);
return; return;
...@@ -922,7 +929,7 @@ Operates data in the database in batches. This API uses a promise to return the ...@@ -922,7 +929,7 @@ Operates data in the database in batches. This API uses a promise to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | -------------------------------| ---- | ------------------------------------------------ | | ---------- | -------------------------------| ---- | ------------------------------------------------ |
| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| | 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. | | operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. |
**Return value** **Return value**
...@@ -939,9 +946,9 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -939,9 +946,9 @@ import featureAbility from '@ohos.ability.featureAbility';
// Select the operations to be performed on the database according to the DataAbilityOperation array. // Select the operations to be performed on the database according to the DataAbilityOperation array.
let op=new Array(); let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.jsapidemo.UserDataAbility" 'dataability:///com.example.jsapidemo.UserDataAbility');
); dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility',
dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { op).then((data) => {
console.info('Operation succeeded: ' + data); console.info('Operation succeeded: ' + data);
}).catch((error) => { }).catch((error) => {
console.error('Operation failed. Cause: ' + error); console.error('Operation failed. Cause: ' + error);
......
...@@ -11,67 +11,64 @@ The **DataAbilityResult** module defines the operation result on DataAbilities. ...@@ -11,67 +11,64 @@ The **DataAbilityResult** module defines the operation result on DataAbilities.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| uri? | string | No | URI of the DataAbility. 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. | | count? | number | No | Number of rows affected by the operation. |
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility';
// Perform database operations in batches. let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility');
function executeBatchOperation() { let DAHelper;
let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); try {
let DAHelper; DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri);
try { if (DAHelper == null) {
DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); console.error('DAHelper is null');
if (DAHelper == null) {
console.error('DAHelper is null');
return;
}
} catch (err) {
console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err));
return; return;
} }
} catch (err) {
console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err));
return;
}
let valueBucket = { let valueBucket = {
"name": "DataAbilityHelperTest", 'name': 'DataAbilityHelperTest',
"age": 24, 'age': 24,
"salary": 2024.20, 'salary': 2024.20,
}; };
let operations = [ let operations = [
{ {
uri: dataAbilityUri, uri: dataAbilityUri,
type: featureAbility.DataAbilityOperationType.TYPE_INSERT, type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
valuesBucket: valueBucket, valuesBucket: valueBucket,
predicates: null, predicates: null,
expectedCount: 1, expectedCount: 1,
PredicatesBackReferences: {}, PredicatesBackReferences: {},
interrupted: true, interrupted: true,
}, },
{ {
uri: dataAbilityUri, uri: dataAbilityUri,
type: featureAbility.DataAbilityOperationType.TYPE_INSERT, type: featureAbility.DataAbilityOperationType.TYPE_INSERT,
valuesBucket: valueBucket, valuesBucket: valueBucket,
predicates: null, predicates: null,
expectedCount: 1, expectedCount: 1,
PredicatesBackReferences: {}, PredicatesBackReferences: {},
interrupted: true, interrupted: true,
} }
]; ];
try { try {
DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { let promise = DAHelper.executeBatch(dataAbilityUri, operations).then((data) => {
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let dataAbilityResult = data[i]; let dataAbilityResult = data[i];
console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri);
console.log('dataAbilityResult.count: ' + dataAbilityResult.count); console.log('dataAbilityResult.count: ' + dataAbilityResult.count);
} }
}).catch(err => { }).catch(err => {
console.error('executeBatch error: ' + JSON.stringify(err));
});
} catch (err) {
console.error('executeBatch error: ' + JSON.stringify(err)); console.error('executeBatch error: ' + JSON.stringify(err));
} });
} catch (err) {
console.error('executeBatch error: ' + JSON.stringify(err));
} }
``` ```
...@@ -16,31 +16,29 @@ The **StartAbilityParameter** module defines the parameters for starting an abil ...@@ -16,31 +16,29 @@ The **StartAbilityParameter** module defines the parameters for starting an abil
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility';
let Want = { let Want = {
bundleName: "com.example.abilityStartSettingApp2", bundleName: 'com.example.abilityStartSettingApp2',
abilityName: "com.example.abilityStartSettingApp.EntryAbility", abilityName: 'com.example.abilityStartSettingApp.MainAbility',
} };
let abilityStartSetting ={ let abilityStartSetting ={
[featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400], [featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400],
[featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] : [featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] :
featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED,
[featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1,
} };
let startAbilityParameter = { let startAbilityParameter = {
want : Want, want : Want,
abilityStartSetting : abilityStartSetting abilityStartSetting : abilityStartSetting
} };
try { featureAbility.startAbility(startAbilityParameter, (err, data)=>{
featureAbility.startAbility(startAbilityParameter, (err, data) => { console.log('errCode : ' + JSON.stringify(err));
console.log('errCode : ' + JSON.stringify(err)); console.log('data : ' + JSON.stringify(data));
console.log('data : ' + JSON.stringify(data));
});
} catch(error) { } catch(error) {
console.log("startAbility error: " + JSON.stringify(error)); console.log('startAbility error: ' + JSON.stringify(error));
} }
``` ```
...@@ -4,21 +4,21 @@ Want is a carrier for information transfer between objects (application componen ...@@ -4,21 +4,21 @@ Want is a carrier for information transfer between objects (application componen
> **NOTE** > **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 are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | | deviceId | string | No | ID of the device running the ability. |
| bundleName | string | No | Bundle name.| | bundleName | string | No | Bundle name. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.|
| 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.| | 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**.| | 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. | | 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#wantconstantflags). | | 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#wantconstantflags). |
| 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#wantconstantaction). 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). | | 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. | | 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.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files. |
| 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#wantconstantentity). | | 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<sup>9+</sup> | string | No | Module to which the ability belongs.| | moduleName<sup>9+</sup> | string | No | Module to which the ability belongs.|
**Example** **Example**
...@@ -27,42 +27,42 @@ Want is a carrier for information transfer between objects (application componen ...@@ -27,42 +27,42 @@ Want is a carrier for information transfer between objects (application componen
```ts ```ts
let want = { let want = {
"deviceId": "", // An empty deviceId indicates the local device. 'deviceId': '', // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication", 'bundleName': 'com.extreme.test',
"abilityName": "EntryAbility", 'abilityName': 'MainAbility',
"moduleName": "entry" // moduleName is optional. 'moduleName': 'entry' // moduleName is optional.
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code)
}) });
``` ```
- Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): - Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility):
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';;
// ... // ...
let fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync('/data/storage/el2/base/haps/pic.png');
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(e)); console.log('openSync fail:' + JSON.stringify(e));
} }
let want = { let want = {
"deviceId": "", // An empty deviceId indicates the local device. 'deviceId': '', // An empty deviceId indicates the local device.
"bundleName": "com.example.myapplication", 'bundleName': 'com.extreme.test',
"abilityName": "EntryAbility", 'abilityName': 'MainAbility',
"moduleName": "entry", // moduleName is optional. 'moduleName': 'entry', // moduleName is optional.
"parameters": { 'parameters': {
"keyFd":{"type":"FD", "value":fd} 'keyFd':{'type':'FD', 'value':fd}
} }
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code) console.log('error.code = ' + error.code)
}) });
// ... // ...
``` ```
......
...@@ -14,9 +14,9 @@ The **Context** object is created in a **featureAbility** and returned through i ...@@ -14,9 +14,9 @@ The **Context** object is created in a **featureAbility** and returned through i
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getOrCreateLocalDir().then((data) => { context.getOrCreateLocalDir().then((data) => {
console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); console.info('getOrCreateLocalDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -40,9 +40,9 @@ If this API is called for the first time, a root directory will be created. ...@@ -40,9 +40,9 @@ If this API is called for the first time, a root directory will be created.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getOrCreateLocalDir((err, data)=>{ context.getOrCreateLocalDir((err, data)=>{
console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getOrCreateLocalDir err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -68,9 +68,9 @@ If this API is called for the first time, a root directory will be created. ...@@ -68,9 +68,9 @@ If this API is called for the first time, a root directory will be created.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getOrCreateLocalDir().then((data) => { context.getOrCreateLocalDir().then((data) => {
console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); console.info('getOrCreateLocalDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -94,15 +94,14 @@ Verifies whether a specific PID and UID have the given permission. This API uses ...@@ -94,15 +94,14 @@ Verifies whether a specific PID and UID have the given permission. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle.bundleManager'; import bundle from '@ohos.bundle';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{
context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ context.verifyPermission('com.example.permission', {uid:datainfo.uid}, (err, data) =>{
console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(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).
...@@ -125,9 +124,9 @@ Verifies whether the current PID and UID have the given permission. This API use ...@@ -125,9 +124,9 @@ Verifies whether the current PID and UID have the given permission. This API use
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.verifyPermission("com.example.permission", (err, data) =>{ context.verifyPermission('com.example.permission', (err, data) =>{
console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('verifyPermission err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -156,10 +155,10 @@ Verifies whether a specific PID and UID have the given permission. This API uses ...@@ -156,10 +155,10 @@ Verifies whether a specific PID and UID have the given permission. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var Permission = {pid:1}; let Permission = {pid:1};
context.verifyPermission('com.context.permission',Permission).then((data) => { context.verifyPermission('com.context.permission',Permission).then((data) => {
console.info("verifyPermission data: " + JSON.stringify(data)); console.info('verifyPermission data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -185,16 +184,16 @@ Requests certain permissions from the system. This API uses an asynchronous call ...@@ -185,16 +184,16 @@ Requests certain permissions from the system. This API uses an asynchronous call
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser( context.requestPermissionsFromUser(
["com.example.permission1", ['com.example.permission1',
"com.example.permission2", 'com.example.permission2',
"com.example.permission3", 'com.example.permission3',
"com.example.permission4", 'com.example.permission4',
"com.example.permission5"], 'com.example.permission5'],
1, 1,
(err, data) => { (err, data) => {
console.info("requestPermissionsFromUser err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('requestPermissionsFromUser err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
} }
); );
``` ```
...@@ -225,15 +224,15 @@ Requests certain permissions from the system. This API uses a promise to return ...@@ -225,15 +224,15 @@ Requests certain permissions from the system. This API uses a promise to return
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser( context.requestPermissionsFromUser(
["com.example.permission1", ['com.example.permission1',
"com.example.permission2", 'com.example.permission2',
"com.example.permission3", 'com.example.permission3',
"com.example.permission4", 'com.example.permission4',
"com.example.permission5"], 'com.example.permission5'],
1).then((data)=>{ 1).then((data)=>{
console.info("requestPermissionsFromUser data: " + JSON.stringify(data)); console.info('requestPermissionsFromUser data: ' + JSON.stringify(data));
} }
); );
``` ```
...@@ -252,15 +251,15 @@ Obtains information about the current application. This API uses an asynchronous ...@@ -252,15 +251,15 @@ Obtains information about the current application. This API uses an asynchronous
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------ | | -------- | ------------------------------- | ---- | ------------ |
| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | Callback used to return the application information.| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getApplicationInfo((err, data) => { context.getApplicationInfo((err, data) => {
console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getApplicationInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -284,9 +283,9 @@ Obtains information about the current application. This API uses a promise to re ...@@ -284,9 +283,9 @@ Obtains information about the current application. This API uses a promise to re
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getApplicationInfo().then((data) => { context.getApplicationInfo().then((data) => {
console.info("getApplicationInfo data: " + JSON.stringify(data)); console.info('getApplicationInfo data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -310,9 +309,9 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback ...@@ -310,9 +309,9 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getBundleName((err, data) => { context.getBundleName((err, data) => {
console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getBundleName err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -336,9 +335,9 @@ Obtains the bundle name of this ability. This API uses a promise to return the r ...@@ -336,9 +335,9 @@ Obtains the bundle name of this ability. This API uses a promise to return the r
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getBundleName().then((data) => { context.getBundleName().then((data) => {
console.info("getBundleName data: " + JSON.stringify(data)); console.info('getBundleName data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -354,15 +353,15 @@ Obtains the display orientation of this ability. This API uses an asynchronous c ...@@ -354,15 +353,15 @@ Obtains the display orientation of this ability. This API uses an asynchronous c
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------ |
| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Yes | Callback used to return the display orientation.| | callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getDisplayOrientation((err, data) => { context.getDisplayOrientation((err, data) => {
console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getDisplayOrientation err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -378,15 +377,15 @@ Obtains the display orientation of this ability. This API uses a promise to retu ...@@ -378,15 +377,15 @@ Obtains the display orientation of this ability. This API uses a promise to retu
| Type | Description | | Type | Description |
| ---------------------------------------- | --------- | | ---------------------------------------- | --------- |
| Promise\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Promise used to return the display orientation.| | Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getDisplayOrientation().then((data) => { context.getDisplayOrientation().then((data) => {
console.info("getDisplayOrientation data: " + JSON.stringify(data)); console.info('getDisplayOrientation data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -408,9 +407,9 @@ Obtains the external cache directory of the application. This API uses an asynch ...@@ -408,9 +407,9 @@ Obtains the external cache directory of the application. This API uses an asynch
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getExternalCacheDir((err, data) => { context.getExternalCacheDir((err, data) => {
console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getExternalCacheDir err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -432,9 +431,9 @@ Obtains the external cache directory of the application. This API uses a promise ...@@ -432,9 +431,9 @@ Obtains the external cache directory of the application. This API uses a promise
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getExternalCacheDir().then((data) => { context.getExternalCacheDir().then((data) => {
console.info("getExternalCacheDir data: " + JSON.stringify(data)); console.info('getExternalCacheDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -450,7 +449,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal ...@@ -450,7 +449,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ------------ | | ----------- | ---------------------------------------- | ---- | ------------ |
| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | Display orientation to set.| | orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the display orientation. | | callback | AsyncCallback\<void> | Yes | Callback used to return the display orientation. |
**Example** **Example**
...@@ -458,10 +457,10 @@ Sets the display orientation for this ability. This API uses an asynchronous cal ...@@ -458,10 +457,10 @@ Sets the display orientation for this ability. This API uses an asynchronous cal
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle'; import bundle from '@ohos.bundle';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var orientation = bundle.DisplayOrientation.UNSPECIFIED; let orientation=bundle.DisplayOrientation.UNSPECIFIED
context.setDisplayOrientation(orientation, (err) => { context.setDisplayOrientation(orientation, (err) => {
console.info("setDisplayOrientation err: " + JSON.stringify(err)); console.info('setDisplayOrientation err: ' + JSON.stringify(err));
}); });
``` ```
...@@ -477,7 +476,7 @@ Sets the display orientation for this ability. This API uses a promise to return ...@@ -477,7 +476,7 @@ Sets the display orientation for this ability. This API uses a promise to return
| Type | Description | | Type | Description |
| ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- |
| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | | orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) |
| Promise\<void> | Promise used to return the display orientation. | | Promise\<void> | Promise used to return the display orientation. |
**Example** **Example**
...@@ -485,10 +484,10 @@ Sets the display orientation for this ability. This API uses a promise to return ...@@ -485,10 +484,10 @@ Sets the display orientation for this ability. This API uses a promise to return
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle'; import bundle from '@ohos.bundle';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var orientation = bundle.DisplayOrientation.UNSPECIFIED; let orientation=bundle.DisplayOrientation.UNSPECIFIED
context.setDisplayOrientation(orientation).then((data) => { context.setDisplayOrientation(orientation).then((data) => {
console.info("setDisplayOrientation data: " + JSON.stringify(data)); console.info('setDisplayOrientation data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -511,10 +510,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat ...@@ -511,10 +510,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var show = true; let show=true
context.setShowOnLockScreen(show, (err) => { context.setShowOnLockScreen(show, (err) => {
console.info("setShowOnLockScreen err: " + JSON.stringify(err)); console.info('setShowOnLockScreen err: ' + JSON.stringify(err));
}); });
``` ```
...@@ -542,10 +541,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat ...@@ -542,10 +541,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var show = true; let show=true
context.setShowOnLockScreen(show).then((data) => { context.setShowOnLockScreen(show).then((data) => {
console.info("setShowOnLockScreen data: " + JSON.stringify(data)); console.info('setShowOnLockScreen data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -568,10 +567,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses ...@@ -568,10 +567,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var wakeUp = true; let wakeUp=true
context.setWakeUpScreen(wakeUp, (err) => { context.setWakeUpScreen(wakeUp, (err) => {
console.info("setWakeUpScreen err: " + JSON.stringify(err)); console.info('setWakeUpScreen err: ' + JSON.stringify(err));
}); });
``` ```
...@@ -599,10 +598,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses ...@@ -599,10 +598,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
var wakeUp = true; let wakeUp=true
context.setWakeUpScreen(wakeUp).then((data) => { context.setWakeUpScreen(wakeUp).then((data) => {
console.info("setWakeUpScreen data: " + JSON.stringify(data)); console.info('setWakeUpScreen data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -627,9 +626,9 @@ Obtains information about the current process, including the PID and process nam ...@@ -627,9 +626,9 @@ Obtains information about the current process, including the PID and process nam
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getProcessInfo((err, data) => { context.getProcessInfo((err, data) => {
console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getProcessInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -653,9 +652,9 @@ Obtains information about the current process, including the PID and process nam ...@@ -653,9 +652,9 @@ Obtains information about the current process, including the PID and process nam
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getProcessInfo().then((data) => { context.getProcessInfo().then((data) => {
console.info("getProcessInfo data: " + JSON.stringify(data)); console.info('getProcessInfo data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -675,15 +674,15 @@ This API is available only to Page abilities. ...@@ -675,15 +674,15 @@ This API is available only to Page abilities.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | -------------------------------------- | | -------- | --------------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| | callback | AsyncCallback\<[ElementName](js-apis-bundle-ElementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getElementName((err, data) => { context.getElementName((err, data) => {
console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getElementName err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -703,15 +702,15 @@ This API is available only to Page abilities. ...@@ -703,15 +702,15 @@ This API is available only to Page abilities.
| Type | Description | | Type | Description |
| --------------------- | ------------------------------------ | | --------------------- | ------------------------------------ |
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| | Promise\<[ElementName](js-apis-bundle-ElementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getElementName().then((data) => { context.getElementName().then((data) => {
console.info("getElementName data: " + JSON.stringify(data)); console.info('getElementName data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -733,9 +732,9 @@ Obtains the name of the current process. This API uses an asynchronous callback ...@@ -733,9 +732,9 @@ Obtains the name of the current process. This API uses an asynchronous callback
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getProcessName((err, data) => { context.getProcessName((err, data) => {
console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getProcessName err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -759,9 +758,9 @@ Obtains the name of the current process. This API uses a promise to return the r ...@@ -759,9 +758,9 @@ Obtains the name of the current process. This API uses a promise to return the r
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getProcessName().then((data) => { context.getProcessName().then((data) => {
console.info("getProcessName data: " + JSON.stringify(data)); console.info('getProcessName data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -785,9 +784,9 @@ Obtains the bundle name of the caller ability. This API uses an asynchronous cal ...@@ -785,9 +784,9 @@ Obtains the bundle name of the caller ability. This API uses an asynchronous cal
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getCallingBundle((err, data) => { context.getCallingBundle((err, data) => {
console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getCallingBundle err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -811,9 +810,9 @@ Obtains the bundle name of the caller ability. This API uses a promise to return ...@@ -811,9 +810,9 @@ Obtains the bundle name of the caller ability. This API uses a promise to return
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getCallingBundle().then((data) => { context.getCallingBundle().then((data) => {
console.info("getCallingBundle data: " + JSON.stringify(data)); console.info('getCallingBundle data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -835,9 +834,9 @@ Obtains the cache directory of the application in the internal storage. This API ...@@ -835,9 +834,9 @@ Obtains the cache directory of the application in the internal storage. This API
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getCacheDir((err, data) => { context.getCacheDir((err, data) => {
console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getCacheDir err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -859,9 +858,9 @@ Obtains the cache directory of the application in the internal storage. This API ...@@ -859,9 +858,9 @@ Obtains the cache directory of the application in the internal storage. This API
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getCacheDir().then((data) => { context.getCacheDir().then((data) => {
console.info("getCacheDir data: " + JSON.stringify(data)); console.info('getCacheDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -883,9 +882,9 @@ Obtains the file directory of the application in the internal storage. This API ...@@ -883,9 +882,9 @@ Obtains the file directory of the application in the internal storage. This API
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir((err, data) => { context.getFilesDir((err, data) => {
console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getFilesDir err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -907,9 +906,9 @@ Obtains the file directory of the application in the internal storage. This API ...@@ -907,9 +906,9 @@ Obtains the file directory of the application in the internal storage. This API
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir().then((data) => { context.getFilesDir().then((data) => {
console.info("getFilesDir data: " + JSON.stringify(data)); console.info('getFilesDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -933,9 +932,9 @@ If the distributed file path does not exist, the system will create one and retu ...@@ -933,9 +932,9 @@ If the distributed file path does not exist, the system will create one and retu
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getOrCreateDistributedDir((err, data) => { context.getOrCreateDistributedDir((err, data) => {
console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getOrCreateDistributedDir err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -959,9 +958,9 @@ If the distributed file path does not exist, the system will create one and retu ...@@ -959,9 +958,9 @@ If the distributed file path does not exist, the system will create one and retu
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getOrCreateDistributedDir().then((data) => { context.getOrCreateDistributedDir().then((data) => {
console.info("getOrCreateDistributedDir data: " + JSON.stringify(data)); console.info('getOrCreateDistributedDir data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -983,9 +982,9 @@ Obtains the application type. This API uses an asynchronous callback to return t ...@@ -983,9 +982,9 @@ Obtains the application type. This API uses an asynchronous callback to return t
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAppType((err, data) => { context.getAppType((err, data) => {
console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getAppType err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1007,9 +1006,9 @@ Obtains the application type. This API uses a promise to return the result. ...@@ -1007,9 +1006,9 @@ Obtains the application type. This API uses a promise to return the result.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAppType().then((data) => { context.getAppType().then((data) => {
console.info("getAppType data: " + JSON.stringify(data)); console.info('getAppType data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1025,15 +1024,15 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron ...@@ -1025,15 +1024,15 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------------- | | -------- | ---------------------------------------- | ---- | --------------------------------------- |
| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| | callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getHapModuleInfo((err, data) => { context.getHapModuleInfo((err, data) => {
console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getHapModuleInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1049,15 +1048,15 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to ...@@ -1049,15 +1048,15 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------ | | ---------------------------------------- | ------------------ |
| Promise\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| | Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getHapModuleInfo().then((data) => { context.getHapModuleInfo().then((data) => {
console.info("getHapModuleInfo data: " + JSON.stringify(data)); console.info('getHapModuleInfo data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1079,9 +1078,9 @@ Obtains the version information of the application. This API uses an asynchronou ...@@ -1079,9 +1078,9 @@ Obtains the version information of the application. This API uses an asynchronou
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAppVersionInfo((err, data) => { context.getAppVersionInfo((err, data) => {
console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getAppVersionInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1103,9 +1102,9 @@ Obtains the version information of the application. This API uses a promise to r ...@@ -1103,9 +1102,9 @@ Obtains the version information of the application. This API uses a promise to r
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAppVersionInfo().then((data) => { context.getAppVersionInfo().then((data) => {
console.info("getAppVersionInfo data: " + JSON.stringify(data)); console.info('getAppVersionInfo data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1121,15 +1120,15 @@ Obtains information about this ability. This API uses an asynchronous callback t ...@@ -1121,15 +1120,15 @@ Obtains information about this ability. This API uses an asynchronous callback t
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------------- | | -------- | ---------------------------------------- | ---- | --------------------------------------- |
| callback | AsyncCallback\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | Callback used to return the ability information.| | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAbilityInfo((err, data) => { context.getAbilityInfo((err, data) => {
console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('getAbilityInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1145,15 +1144,15 @@ Obtains information about this ability. This API uses a promise to return the re ...@@ -1145,15 +1144,15 @@ Obtains information about this ability. This API uses a promise to return the re
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------ | | ---------------------------------------- | ------------------ |
| Promise\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Promise used to return the ability information.| | Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.|
**Example** **Example**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getAbilityInfo().then((data) => { context.getAbilityInfo().then((data) => {
console.info("getAbilityInfo data: " + JSON.stringify(data)); console.info('getAbilityInfo data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1175,7 +1174,7 @@ Obtains the context of the application. ...@@ -1175,7 +1174,7 @@ Obtains the context of the application.
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext().getApplicationContext(); let context = featureAbility.getContext().getApplicationContext();
``` ```
## Context.isUpdatingConfigurations<sup>7+</sup> ## Context.isUpdatingConfigurations<sup>7+</sup>
...@@ -1196,9 +1195,9 @@ Checks whether the configuration of this ability is being updated. This API uses ...@@ -1196,9 +1195,9 @@ Checks whether the configuration of this ability is being updated. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.isUpdatingConfigurations((err, data) => { context.isUpdatingConfigurations((err, data) => {
console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info('isUpdatingConfigurations err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1220,9 +1219,9 @@ Checks whether the configuration of this ability is being updated. This API uses ...@@ -1220,9 +1219,9 @@ Checks whether the configuration of this ability is being updated. This API uses
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.isUpdatingConfigurations().then((data) => { context.isUpdatingConfigurations().then((data) => {
console.info("isUpdatingConfigurations data: " + JSON.stringify(data)); console.info('isUpdatingConfigurations data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1244,7 +1243,7 @@ Notifies the system of the time required to draw this page function. This API us ...@@ -1244,7 +1243,7 @@ Notifies the system of the time required to draw this page function. This API us
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.printDrawnCompleted((err) => { context.printDrawnCompleted((err) => {
console.error('printDrawnCompleted err: ' + JSON.stringify(err)); console.error('printDrawnCompleted err: ' + JSON.stringify(err));
}); });
...@@ -1268,9 +1267,9 @@ Notifies the system of the time required to draw this page function. This API us ...@@ -1268,9 +1267,9 @@ Notifies the system of the time required to draw this page function. This API us
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.printDrawnCompleted().then((data) => { context.printDrawnCompleted().then((data) => {
console.info("printDrawnCompleted data: " + JSON.stringify(data)); console.info('printDrawnCompleted data: ' + JSON.stringify(data));
}); });
``` ```
...@@ -1293,13 +1292,3 @@ context.printDrawnCompleted().then((data) => { ...@@ -1293,13 +1292,3 @@ context.printDrawnCompleted().then((data) => {
| requestCode | Read-only | number | Yes | Request code passed.| | requestCode | Read-only | number | Yes | Request code passed.|
| permissions | Read-only | Array\<string> | Yes | Permissions requested. | | permissions | Read-only | Array\<string> | Yes | Permissions requested. |
| authResults | Read-only | Array\<number> | Yes | Permission request result. | | authResults | Read-only | Array\<number> | Yes | Permission request result. |
## AppVersionInfo<sup>7+</sup>
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable | Writable | Description |
| ----------- | ------ | ---- | ---- | ------- |
| appName | string | Yes | No | Module name. |
| versionCode | number | Yes | No | Module description.|
| versionName | string | Yes | No | Module description ID.|
...@@ -3,10 +3,8 @@ ...@@ -3,10 +3,8 @@
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. 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** > **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 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 **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -19,10 +17,13 @@ The **ProcessInfo** module defines process information. You can use [getProcessI ...@@ -19,10 +17,13 @@ The **ProcessInfo** module defines process information. You can use [getProcessI
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getProcessInfo((err, data) => { context.getProcessInfo((err, data) => {
console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); if (err.code !== 0) {
let pid = data.pid; console.info('getProcessInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data));
let processName = data.processName; let pid = data.pid;
let processName = data.processName;
}
}); });
``` ```
...@@ -35,20 +35,20 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r ...@@ -35,20 +35,20 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (err : any) => { abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
console.info("addAbilityMonitor callback"); console.info('addAbilityMonitor callback');
}); });
``` ```
...@@ -75,20 +75,20 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul ...@@ -75,20 +75,20 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor).then(() => { abilityDelegator.addAbilityMonitor(monitor).then(() => {
console.info("addAbilityMonitor promise"); console.info('addAbilityMonitor promise');
}); });
``` ```
...@@ -112,20 +112,20 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t ...@@ -112,20 +112,20 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { abilityDelegator.removeAbilityMonitor(monitor, (err : any) => {
console.info("removeAbilityMonitor callback"); console.info('removeAbilityMonitor callback');
}); });
``` ```
...@@ -154,20 +154,20 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re ...@@ -154,20 +154,20 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re
- Example - Example
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityMonitor(monitor).then(() => { abilityDelegator.removeAbilityMonitor(monitor).then(() => {
console.info("removeAbilityMonitor promise"); console.info('removeAbilityMonitor promise');
}); });
``` ```
...@@ -191,20 +191,20 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance ...@@ -191,20 +191,20 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => {
console.info("waitAbilityMonitor callback"); console.info('waitAbilityMonitor callback');
}); });
``` ```
...@@ -227,21 +227,21 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo ...@@ -227,21 +227,21 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => { abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => {
console.info("waitAbilityMonitor callback"); console.info('waitAbilityMonitor callback');
}); });
``` ```
...@@ -271,20 +271,20 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo ...@@ -271,20 +271,20 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => {
console.info("waitAbilityMonitor promise"); console.info('waitAbilityMonitor promise');
}); });
``` ```
...@@ -307,10 +307,10 @@ Obtains the application context. ...@@ -307,10 +307,10 @@ Obtains the application context.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
var context = abilityDelegator.getAppContext(); let context = abilityDelegator.getAppContext();
``` ```
...@@ -338,15 +338,15 @@ Obtains the lifecycle state of an ability. ...@@ -338,15 +338,15 @@ Obtains the lifecycle state of an ability.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
var state = abilityDelegator.getAbilityState(ability); let state = abilityDelegator.getAbilityState(ability);
console.info("getAbilityState" + state); console.info('getAbilityState' + state);
}); });
``` ```
...@@ -369,12 +369,12 @@ Obtains the top ability of this application. This API uses an asynchronous callb ...@@ -369,12 +369,12 @@ Obtains the top ability of this application. This API uses an asynchronous callb
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
}); });
``` ```
...@@ -398,12 +398,12 @@ Obtains the top ability of this application. This API uses a promise to return t ...@@ -398,12 +398,12 @@ Obtains the top ability of this application. This API uses a promise to return t
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility().then((data : any) => { abilityDelegator.getCurrentTopAbility().then((data : any) => {
console.info("getCurrentTopAbility promise"); console.info('getCurrentTopAbility promise');
ability = data; ability = data;
}); });
``` ```
...@@ -428,15 +428,15 @@ Starts an ability. This API uses an asynchronous callback to return the result. ...@@ -428,15 +428,15 @@ Starts an ability. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var want = { let want = {
bundleName: "bundleName", bundleName: 'bundleName',
abilityName: "abilityName" abilityName: 'abilityName'
}; };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.startAbility(want, (err : any, data : any) => { abilityDelegator.startAbility(want, (err : any, data : any) => {
console.info("startAbility callback"); console.info('startAbility callback');
}); });
``` ```
...@@ -465,15 +465,15 @@ Starts an ability. This API uses a promise to return the result. ...@@ -465,15 +465,15 @@ Starts an ability. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var want = { let want = {
bundleName: "bundleName", bundleName: 'bundleName',
abilityName: "abilityName" abilityName: 'abilityName'
}; };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.startAbility(want).then((data: any) => { abilityDelegator.startAbility(want).then((data: any) => {
console.info("startAbility promise"); console.info('startAbility promise');
}); });
``` ```
...@@ -497,15 +497,15 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an ...@@ -497,15 +497,15 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => { abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => {
console.info("doAbilityForeground callback"); console.info('doAbilityForeground callback');
}); });
}); });
``` ```
...@@ -535,15 +535,15 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p ...@@ -535,15 +535,15 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
abilityDelegator.doAbilityForeground(ability).then((data : any) => { abilityDelegator.doAbilityForeground(ability).then((data : any) => {
console.info("doAbilityForeground promise"); console.info('doAbilityForeground promise');
}); });
}); });
``` ```
...@@ -568,15 +568,15 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an ...@@ -568,15 +568,15 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => { abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => {
console.info("doAbilityBackground callback"); console.info('doAbilityBackground callback');
}); });
}); });
``` ```
...@@ -606,15 +606,15 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p ...@@ -606,15 +606,15 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => { abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
console.info("getCurrentTopAbility callback"); console.info('getCurrentTopAbility callback');
ability = data; ability = data;
abilityDelegator.doAbilityBackground(ability).then((data : any) => { abilityDelegator.doAbilityBackground(ability).then((data : any) => {
console.info("doAbilityBackground promise"); console.info('doAbilityBackground promise');
}); });
}); });
``` ```
...@@ -638,8 +638,8 @@ Prints log information to the unit test console. ...@@ -638,8 +638,8 @@ Prints log information to the unit test console.
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = "msg"; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.printSync(msg); abilityDelegator.printSync(msg);
...@@ -665,12 +665,12 @@ Prints log information to the unit test console. This API uses an asynchronous c ...@@ -665,12 +665,12 @@ Prints log information to the unit test console. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = "msg"; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.print(msg, (err : any) => { abilityDelegator.print(msg, (err : any) => {
console.info("print callback"); console.info('print callback');
}); });
``` ```
...@@ -699,12 +699,12 @@ Prints log information to the unit test console. This API uses a promise to retu ...@@ -699,12 +699,12 @@ Prints log information to the unit test console. This API uses a promise to retu
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = "msg"; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.print(msg).then(() => { abilityDelegator.print(msg).then(() => {
console.info("print promise"); console.info('print promise');
}); });
``` ```
...@@ -728,12 +728,12 @@ Executes a shell command. This API uses an asynchronous callback to return the r ...@@ -728,12 +728,12 @@ Executes a shell command. This API uses an asynchronous callback to return the r
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = "cmd"; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => {
console.info("executeShellCommand callback"); console.info('executeShellCommand callback');
}); });
``` ```
...@@ -758,13 +758,13 @@ Executes a shell command with the timeout period specified. This API uses an asy ...@@ -758,13 +758,13 @@ Executes a shell command with the timeout period specified. This API uses an asy
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = "cmd"; let cmd = 'cmd';
var timeout = 100; let timeout = 100;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => {
console.info("executeShellCommand callback"); console.info('executeShellCommand callback');
}); });
``` ```
...@@ -794,13 +794,13 @@ Executes a shell command with the timeout period specified. This API uses a prom ...@@ -794,13 +794,13 @@ Executes a shell command with the timeout period specified. This API uses a prom
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var cmd = "cmd"; let cmd = 'cmd';
var timeout = 100; let timeout = 100;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => {
console.info("executeShellCommand promise"); console.info('executeShellCommand promise');
}); });
``` ```
...@@ -825,12 +825,12 @@ Finishes the test and prints log information to the unit test console. This API ...@@ -825,12 +825,12 @@ Finishes the test and prints log information to the unit test console. This API
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = "msg"; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.finishTest(msg, 0, (err : any) => { abilityDelegator.finishTest(msg, 0, (err : any) => {
console.info("finishTest callback"); console.info('finishTest callback');
}); });
``` ```
...@@ -860,12 +860,12 @@ Finishes the test and prints log information to the unit test console. This API ...@@ -860,12 +860,12 @@ Finishes the test and prints log information to the unit test console. This API
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var msg = "msg"; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.finishTest(msg, 0).then(() => { abilityDelegator.finishTest(msg, 0).then(() => {
console.info("finishTest promise"); console.info('finishTest promise');
}); });
``` ```
...@@ -887,16 +887,16 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes ...@@ -887,16 +887,16 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => { abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => {
console.info("addAbilityStageMonitor callback"); console.info('addAbilityStageMonitor callback');
}); });
``` ```
...@@ -925,16 +925,16 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes ...@@ -925,16 +925,16 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor).then(() => { abilityDelegator.addAbilityStageMonitor(monitor).then(() => {
console.info("addAbilityStageMonitor promise"); console.info('addAbilityStageMonitor promise');
}); });
``` ```
...@@ -956,16 +956,16 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP ...@@ -956,16 +956,16 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => { abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => {
console.info("removeAbilityStageMonitor callback"); console.info('removeAbilityStageMonitor callback');
}); });
``` ```
...@@ -994,16 +994,16 @@ Removes an **AbilityStageMonitor** object from the application memory. This API ...@@ -994,16 +994,16 @@ Removes an **AbilityStageMonitor** object from the application memory. This API
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor).then(() => { abilityDelegator.removeAbilityStageMonitor(monitor).then(() => {
console.info("removeAbilityStageMonitor promise"); console.info('removeAbilityStageMonitor promise');
}); });
``` ```
...@@ -1025,20 +1025,20 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A ...@@ -1025,20 +1025,20 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => { abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback"); console.info('waitAbilityStageMonitor callback');
}); });
``` ```
...@@ -1066,20 +1066,20 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A ...@@ -1066,20 +1066,20 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor).then((data : any) => { abilityDelegator.waitAbilityStageMonitor(monitor).then((data : any) => {
console.info("waitAbilityStageMonitor promise"); console.info('waitAbilityStageMonitor promise');
}); });
``` ```
...@@ -1102,20 +1102,20 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi ...@@ -1102,20 +1102,20 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi
**Example** **Example**
```ts ```ts
var abilityDelegator; let abilityDelegator;
var timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
moduleName: "moduleName", moduleName: 'moduleName',
srcEntrance: "srcEntrance", srcEntrance: 'srcEntrance',
} };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => { abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback"); console.info('waitAbilityStageMonitor callback');
}); });
``` ```
# AbilityDelegatorArgs # AbilityDelegatorArgs
The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegatorArgs** object during the execution of test cases. The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup.
> **NOTE** > **NOTE**
> >
...@@ -28,5 +28,5 @@ Describes the ability delegator arguments. ...@@ -28,5 +28,5 @@ Describes the ability delegator arguments.
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments(); let args = AbilityDelegatorRegistry.getArguments();
``` ```
...@@ -19,6 +19,7 @@ Describes an ability monitor. ...@@ -19,6 +19,7 @@ Describes an ability monitor.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.| | abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.|
| moduleName? | string | Yes | Yes | Name of the module bound to the ability monitor.|
| onAbilityCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is created.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.| | onAbilityCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is created.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.|
| onAbilityForeground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the foreground.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.| | onAbilityForeground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the foreground.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.|
| onAbilityBackground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the background.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.| | onAbilityBackground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the background.<br>If this attribute is not set, the corresponding lifecycle callback cannot be received.|
...@@ -30,19 +31,22 @@ Describes an ability monitor. ...@@ -30,19 +31,22 @@ Describes an ability monitor.
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info('onAbilityCreateCallback');
} }
var monitor = { let monitor = {
abilityName: "abilityname", abilityName: 'abilityname',
moduleName: "moduleName",
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
} };
var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (err : any) => { abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
console.info("addAbilityMonitor callback"); console.info('addAbilityMonitor callback');
}); });
``` ```
...@@ -30,15 +30,15 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( ...@@ -30,15 +30,15 @@ The ability running information is obtained by calling [getAbilityRunningInfos](
```ts ```ts
import abilitymanager from '@ohos.application.abilityManager'; import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => { abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); console.log('getAbilityRunningInfos err: ' + err + ' data: ' + JSON.stringify(data));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let abilityinfo = data[i]; let abilityinfo = data[i];
console.log("abilityinfo.ability: " + JSON.stringify(abilityinfo.ability)); console.log('abilityinfo.ability: ' + JSON.stringify(abilityinfo.ability));
console.log("abilityinfo.pid: " + JSON.stringify(abilityinfo.pid)); console.log('abilityinfo.pid: ' + JSON.stringify(abilityinfo.pid));
console.log("abilityinfo.uid: " + JSON.stringify(abilityinfo.uid)); console.log('abilityinfo.uid: ' + JSON.stringify(abilityinfo.uid));
console.log("abilityinfo.processName: " + JSON.stringify(abilityinfo.processName)); console.log('abilityinfo.processName: ' + JSON.stringify(abilityinfo.processName));
console.log("abilityinfo.startTime: " + JSON.stringify(abilityinfo.startTime)); console.log('abilityinfo.startTime: ' + JSON.stringify(abilityinfo.startTime));
console.log("abilityinfo.abilityState: " + JSON.stringify(abilityinfo.abilityState)); console.log('abilityinfo.abilityState: ' + JSON.stringify(abilityinfo.abilityState));
} }
}); });
``` ```
# AbilityStageContext # AbilityStageContext
The **AbilityStageContext** module, inherited from [Context](js-apis-application-context.md), implements the context of an ability stage. The **AbilityStageContext** module, inherited from [Context](js-apis-inner-application-context.md), implements the context of an ability stage.
This module provides APIs for accessing a specific ability stage. You can use the APIs to obtain the **ModuleInfo** object and environment configuration of an ability stage. This module provides APIs for accessing a specific ability stage. You can use the APIs to obtain the **ModuleInfo** object and environment configuration of an ability stage.
...@@ -28,5 +28,5 @@ class MyAbilityStage extends AbilityStage { ...@@ -28,5 +28,5 @@ class MyAbilityStage extends AbilityStage {
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| | currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.|
| config | [Configuration](js-apis-app-ability-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.|
...@@ -11,15 +11,15 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta ...@@ -11,15 +11,15 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
let monitor = { let monitor = {
moduleName: "feature_as1", moduleName: 'feature_as1',
srcEntrance: "./ets/Application/MyAbilityStage.ts", srcEntrance: './ets/Application/MyAbilityStage.ts',
}; };
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => {
console.info("stageMonitor waitAbilityStageMonitor, abilityStage = " + JSON.stringify(data)); console.info('stageMonitor waitAbilityStageMonitor, abilityStage = ' + JSON.stringify(data));
}); });
``` ```
...@@ -4,32 +4,24 @@ The **AppStateData** module defines the application state data, which can be obt ...@@ -4,32 +4,24 @@ The **AppStateData** module defines the application state data, which can be obt
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This module is marked as @systemapi and not visible to third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------------------- | ------ | ---- | --------- | | ------------------------- | ------ | ---- | --------- |
| bundleName<sup>8+</sup> | string | No | Bundle name.| | bundleName<sup>8+</sup> | string | No | Bundle name.|
| uid<sup>8+</sup> | number | No | UID of the application. | | uid<sup>8+</sup> | number | No | UID of the application. |
| state<sup>8+</sup> | number | No | Application state.<br>**0**: The application is being initialized.<br>**1**: The application has been initialized and is ready.<br>**2**: The application is running in the foreground.<br>**3**: The application is having the focus. (This state is reserved.)<br>**4**: The application is running in the background.<br>**5**: The application has exited.| | state<sup>8+</sup> | number | No | Application state.|
**Example** **Example**
```ts ```ts
import appManager from "@ohos.app.ability.appManager" import appManager from "@ohos.application.appManager";
function getForegroundAppInfos() { appManager.getForegroundApplications((error, data) => {
appManager.getForegroundApplications((error, data) => { for (let i = 0; i < data.length; i++) {
if (error && error.code) { let appStateData = data[i];
console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + console.info('appStateData.bundleName: ' + appStateData.bundleName);
' error.message: ' + JSON.stringify(error.message)); console.info('appStateData.uid: ' + appStateData.uid);
return; console.info('appStateData.state: ' + appStateData.state);
} }
for (let i = 0; i < data.length; i++) { });
let appStateData = data[i];
console.log('appStateData.bundleName: ' + appStateData.bundleName);
console.log('appStateData.uid: ' + appStateData.uid);
console.log('appStateData.state: ' + appStateData.state);
}
});
}
``` ```
...@@ -15,9 +15,9 @@ Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContex ...@@ -15,9 +15,9 @@ Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContex
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
``` ```
## ApplicationContext.registerAbilityLifecycleCallback ## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback)
registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**; on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**;
Registers a listener to monitor the ability lifecycle of the application. Registers a listener to monitor the ability lifecycle of the application.
...@@ -27,6 +27,7 @@ Registers a listener to monitor the ability lifecycle of the application. ...@@ -27,6 +27,7 @@ Registers a listener to monitor the ability lifecycle of the application.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ | | ------------------------ | -------- | ---- | ------------------------------ |
| type | 'abilityLifecycle' | Yes | Event type.|
| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| | callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value** **Return value**
...@@ -40,56 +41,56 @@ Registers a listener to monitor the ability lifecycle of the application. ...@@ -40,56 +41,56 @@ Registers a listener to monitor the ability lifecycle of the application.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
var lifecycleId; let lifecycleId;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate() { onCreate() {
console.log("MyAbility onCreate") console.log('MyAbility onCreate');
let AbilityLifecycleCallback = { let AbilityLifecycleCallback = {
onAbilityCreate(ability) { onAbilityCreate(ability) {
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onAbilityCreate ability:' + ability);
}, },
onWindowStageCreate(ability, windowStage) { onWindowStageCreate(ability, windowStage) {
console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onWindowStageCreate ability:' + ability);
console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); console.log('AbilityLifecycleCallback onWindowStageCreate windowStage:' + windowStage);
}, },
onWindowStageActive(ability, windowStage) { onWindowStageActive(ability, windowStage) {
console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onWindowStageActive ability:' + ability);
console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); console.log('AbilityLifecycleCallback onWindowStageActive windowStage:' + windowStage);
}, },
onWindowStageInactive(ability, windowStage) { onWindowStageInactive(ability, windowStage) {
console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onWindowStageInactive ability:' + ability);
console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); console.log('AbilityLifecycleCallback onWindowStageInactive windowStage:' + windowStage);
}, },
onWindowStageDestroy(ability, windowStage) { onWindowStageDestroy(ability, windowStage) {
console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onWindowStageDestroy ability:' + ability);
console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage:' + windowStage);
}, },
onAbilityDestroy(ability) { onAbilityDestroy(ability) {
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onAbilityDestroy ability:' + ability);
}, },
onAbilityForeground(ability) { onAbilityForeground(ability) {
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onAbilityForeground ability:' + ability);
}, },
onAbilityBackground(ability) { onAbilityBackground(ability) {
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onAbilityBackground ability:' + ability);
}, },
onAbilityContinue(ability) { onAbilityContinue(ability) {
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); console.log('AbilityLifecycleCallback onAbilityContinue ability:' + ability);
} }
} }
// 1. Obtain applicationContext through the context attribute. // 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// 2. Use applicationContext to register a listener for the ability lifecycle in the application. // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId));
} }
} }
``` ```
## ApplicationContext.unregisterAbilityLifecycleCallback ## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback<void>)
unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; off(type: 'abilityLifecycle', callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
Deregisters the listener that monitors the ability lifecycle of the application. Deregisters the listener that monitors the ability lifecycle of the application.
...@@ -99,6 +100,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. ...@@ -99,6 +100,7 @@ Deregisters the listener that monitors the ability lifecycle of the application.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- | | ------------- | -------- | ---- | -------------------------- |
| type | 'abilityLifecycle' | Yes | Event type.|
| callbackId | number | Yes | ID of the listener to deregister.| | callbackId | number | Yes | ID of the listener to deregister.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
...@@ -107,22 +109,53 @@ Deregisters the listener that monitors the ability lifecycle of the application. ...@@ -107,22 +109,53 @@ Deregisters the listener that monitors the ability lifecycle of the application.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
var lifecycleId; let lifecycleId;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onDestroy() { onDestroy() {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
console.log("stage applicationContext: " + JSON.stringify(applicationContext)); console.log('stage applicationContext: ' + applicationContext);
applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { applicationContext.off(type: 'abilityLifecycle', lifecycleId, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); console.log('unregisterAbilityLifecycleCallback success, err: ' + JSON.stringify(error));
}); });
} }
} }
``` ```
## ApplicationContext.registerEnvironmentCallback ## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number)
registerEnvironmentCallback(callback: EnvironmentCallback): **number**; off(type: 'abilityLifecycle', callbackId: **number**): **void**;
Deregisters the listener that monitors the ability lifecycle of the application.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| type | 'abilityLifecycle' | Yes | Event type.|
| callbackId | number | Yes | ID of the listener to deregister.|
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
let lifecycleId;
export default class MyAbility extends Ability {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
console.log('stage applicationContext: ' + applicationContext);
applicationContext.off(type: 'abilityLifecycle', lifecycleId);
}
}
```
## ApplicationContext.on(type: 'environment', callback: EnvironmentCallback)
on(type: 'environment', callback: EnvironmentCallback): **number**;
Registers a listener for system environment changes. This API uses an asynchronous callback to return the result. Registers a listener for system environment changes. This API uses an asynchronous callback to return the result.
...@@ -132,6 +165,7 @@ Registers a listener for system environment changes. This API uses an asynchrono ...@@ -132,6 +165,7 @@ Registers a listener for system environment changes. This API uses an asynchrono
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ | | ------------------------ | -------- | ---- | ------------------------------ |
| type | 'environment' | Yes | Event type.|
| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| | callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value** **Return value**
...@@ -145,32 +179,32 @@ Registers a listener for system environment changes. This API uses an asynchrono ...@@ -145,32 +179,32 @@ Registers a listener for system environment changes. This API uses an asynchrono
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
var callbackId; let callbackId;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate() { onCreate() {
console.log("MyAbility onCreate") console.log('MyAbility onCreate')
globalThis.applicationContext = this.context.getApplicationContext(); globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = { let EnvironmentCallback = {
onConfigurationUpdated(config){ onConfigurationUpdated(config){
console.log("onConfigurationUpdated config:" + JSON.stringify(config)); console.log('onConfigurationUpdated config:' + JSON.stringify(config));
}, },
onMemoryLevel(level){ onMemoryLevel(level){
console.log("onMemoryLevel level:" + level); console.log('onMemoryLevel level:' + level);
} }
} }
// 1. Obtain an applicationContext object. // 1. Obtain an applicationContext object.
let applicationContext = globalThis.applicationContext; let applicationContext = globalThis.applicationContext;
// 2. Use applicationContext to register a listener for the ability lifecycle in the application. // 2. Use applicationContext to register a listener for the ability lifecycle in the application.
callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); callbackId = applicationContext.on('environment', EnvironmentCallback);
console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId));
} }
} }
``` ```
## ApplicationContext.unregisterEnvironmentCallback ## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback<void>)
unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; off(type: 'environment', callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.
...@@ -180,6 +214,7 @@ Deregisters the listener for system environment changes. This API uses an asynch ...@@ -180,6 +214,7 @@ Deregisters the listener for system environment changes. This API uses an asynch
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- | | ------------- | -------- | ---- | -------------------------- |
| type | 'environment' | Yes | Event type.|
| callbackId | number | Yes | ID of the listener to deregister. | | callbackId | number | Yes | ID of the listener to deregister. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
...@@ -188,14 +223,154 @@ Deregisters the listener for system environment changes. This API uses an asynch ...@@ -188,14 +223,154 @@ Deregisters the listener for system environment changes. This API uses an asynch
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
var callbackId; let callbackId;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onDestroy() { onDestroy() {
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { applicationContext.off('environment', callbackId, (error, data) => {
console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error));
}); });
} }
} }
``` ```
## ApplicationContext.off(type: 'environment', callbackId: number)
off(type: 'environment', callbackId: **number**, callback: AsyncCallback<**void**>): **void**;
Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| type | 'environment' | Yes | Event type.|
| callbackId | number | Yes | ID of the listener to deregister. |
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
let callbackId;
export default class MyAbility extends Ability {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.off('environment', callbackId);
}
}
```
## ApplicationContext.getRunningProcessInformation<sup>9+</sup>
getRunningProcessInformation(): Promise\<Array\<ProcessInformation>>;
Obtains information about the running processes. This API uses a promise 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.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.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.|
**Example**
```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.getRunningProcessInformation().then((data) => {
console.log('The process running information is:' + JSON.stringify(data));
}).catch((error) => {
console.log('error:' + JSON.stringify(error));
});
```
## ApplicationContext.getRunningProcessInformation<sup>9+</sup>
getRunningProcessInformation(callback: AsyncCallback\<Array\<ProcessInformation>>): void;
Obtains information about the running processes. 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.
**Return value**
| Type| Description|
| -------- | -------- |
|AsyncCallback\<Array\<[ProcessInformation](js-apis-inner-application-processInformation.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.|
**Example**
```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.getRunningProcessInformation((err, data) => {
if (err.code !== 0) {
console.error('getRunningProcessInformation faile, err: ' + JSON.stringify(err));
} else {
console.log('The process running information is:' + JSON.stringify(data));
}
})
```
## ApplicationContext.killProcessesBySelf<sup>9+</sup>
killProcessesBySelf(): Promise<void>;
Kills all the processes where the application is located. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void>> | Promise used to return the result.|
**Example**
```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.killProcessesBySelf().then((data) => {
console.log('The process running information is:' + JSON.stringify(data));
}).catch((error) => {
console.error('error:' + JSON.stringify(error));
});
```
## ApplicationContext.killProcessesBySelf<sup>9+</sup>
killProcessesBySelf(callback: AsyncCallback<void>);
Kills all the processes where the application is located. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type| Description|
| -------- | -------- |
|AsyncCallback\<void\> | Callback used to return the result.|
**Example**
```ts
let applicationContext = this.context.getApplicationContext();
applicationContext.killProcessesBySelf(err => {
if (err.code !== 0) {
console.error('killProcessesBySelf faile, err: ' + JSON.stringify(err));
}
})
```
...@@ -16,7 +16,7 @@ The **ApplicationStateObserver** module defines an observer to listen for applic ...@@ -16,7 +16,7 @@ The **ApplicationStateObserver** module defines an observer to listen for applic
**Example** **Example**
```ts ```ts
import appManager from "@ohos.application.appManager" import appManager from "@ohos.application.appManager";
let applicationStateObserver = { let applicationStateObserver = {
onForegroundApplicationChanged(appStateData) { onForegroundApplicationChanged(appStateData) {
...@@ -34,6 +34,6 @@ let applicationStateObserver = { ...@@ -34,6 +34,6 @@ let applicationStateObserver = {
onProcessStateChanged(processData) { onProcessStateChanged(processData) {
console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData)); console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData));
} }
} };
let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver);
``` ```
...@@ -19,10 +19,10 @@ Take the stage model as an example. You can access the **stageMode** field throu ...@@ -19,10 +19,10 @@ Take the stage model as an example. You can access the **stageMode** field throu
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility { class MainAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// EntryAbility onCreate, isStageMode: true // MainAbility onCreate, isStageMode: true
console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode); console.log('MainAbility onCreate, isStageMode: ' + this.context.stageMode);
} }
} }
``` ```
...@@ -49,7 +49,7 @@ Creates the context based on the bundle name. ...@@ -49,7 +49,7 @@ Creates the context based on the bundle name.
**Example** **Example**
```ts ```ts
let bundleContext = this.context.createBundleContext("com.example.test"); let bundleContext = this.context.createBundleContext('com.example.test');
``` ```
## Context.createModuleContext ## Context.createModuleContext
...@@ -75,9 +75,11 @@ Creates the context based on the module name. ...@@ -75,9 +75,11 @@ Creates the context based on the module name.
**Example** **Example**
```ts ```ts
let moduleContext = this.context.createModuleContext("entry"); let moduleContext = this.context.createModuleContext('entry');
``` ```
## Context.createModuleContext
createModuleContext(bundleName: string, moduleName: string): Context; createModuleContext(bundleName: string, moduleName: string): Context;
Creates the context based on the bundle name and module name. Creates the context based on the bundle name and module name.
...@@ -100,7 +102,7 @@ Creates the context based on the bundle name and module name. ...@@ -100,7 +102,7 @@ Creates the context based on the bundle name and module name.
**Example** **Example**
```ts ```ts
let moduleContext = this.context.createModuleContext("com.example.test", "entry"); let moduleContext = this.context.createModuleContext('com.example.test', 'entry');
``` ```
## Context.getApplicationContext ## Context.getApplicationContext
......
...@@ -2,32 +2,24 @@ ...@@ -2,32 +2,24 @@
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). 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 **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters** | Name | Type | Readable | Writable | Description |
| --------------------- | -------- | ---- | ---- | ------------------ |
| Name| Type| Mandatory| Description| | onContinueDone | function | Yes | No | Mission continuation result. |
| -------- | -------- | -------- | -------- |
| result | number | No| Mission continuation result.|
**Example** **Example**
```ts ```ts
import distributedMissionManager from '@ohos.distributedMissionManager' import distributedMissionManager from '@ohos.distributedMissionManager';
let continueDeviceInfo = { let continueDeviceInfo = {
srcDeviceId: "123", srcDeviceId: '123',
dstDeviceId: "456", dstDeviceId: '456',
missionId: 123, missionId: 123,
wantParam: { wantParam: {
"key":"value" 'key':'value'
} }
}; };
let continueCallback = { let continueCallback = {
...@@ -37,10 +29,9 @@ Called when the mission continuation is complete. ...@@ -37,10 +29,9 @@ Called when the mission continuation is complete.
}; };
distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => {
if (error && error.code) { if (error.code != 0) {
console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + console.error('continueMission failed, cause: ' + JSON.stringify(error))
' error.message: ' + JSON.stringify(error.message)); }
} console.info('continueMission finished')
console.log('continueMission finished');
}) })
``` ```
...@@ -14,15 +14,15 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating ...@@ -14,15 +14,15 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating
**Example** **Example**
```ts ```ts
import distributedMissionManager from '@ohos.distributedMissionManager' import distributedMissionManager from '@ohos.distributedMissionManager';
let continueDeviceInfo = { let continueDeviceInfo = {
srcDeviceId: "123", srcDeviceId: '123',
dstDeviceId: "456", dstDeviceId: '456',
missionId: 123, missionId: 123,
wantParam: { wantParam: {
"key":"value" 'key':'value'
} }
}; };
let continueCallback = { let continueCallback = {
...@@ -32,10 +32,9 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating ...@@ -32,10 +32,9 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating
}; };
distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => {
if (error && error.code) { if (error.code != 0) {
console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + console.error('continueMission failed, cause: ' + JSON.stringify(error))
' error.message: ' + JSON.stringify(error.message)); }
} console.info('continueMission finished')
console.log('continueMission finished');
}) })
``` ```
# ErrorObserver # ErrorObserver
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. The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [registerErrorObserver](js-apis-application-errorManager.md#errormanagerregistererrorobserver) to listen for errors that occur in the current application.
## ErrorObserver.onUnhandledException ## onUnhandledException
onUnhandledException(errMsg: string): void; onUnhandledException(errMsg: string): void;
...@@ -19,18 +19,12 @@ Called when an unhandled exception occurs in the JS runtime. ...@@ -19,18 +19,12 @@ Called when an unhandled exception occurs in the JS runtime.
**Example** **Example**
```ts ```ts
import errorManager from '@ohos.app.ability.errorManager' import errorManager from '@ohos.application.errorManager';
let observer = { let observer = {
onUnhandledException(errorMsg) { onUnhandledException(errorMsg) {
console.log('HXW onUnhandledException, errorMsg: ', errorMsg); console.log('onUnhandledException, errorMsg: ' + JSON.stringify(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));
}
``` ```
...@@ -9,18 +9,16 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri ...@@ -9,18 +9,16 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri
## Usage ## Usage
Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance. Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.application.Ability';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility { func1(){
eventFunc(){ console.log('func1 is called');
console.log("eventFunc is called");
} }
onForeground() { onForeground() {
this.context.eventHub.on("myEvent", this.eventFunc); this.context.eventHub.on('123', this.func1);
} }
} }
``` ```
...@@ -41,36 +39,33 @@ Subscribes to an event. ...@@ -41,36 +39,33 @@ Subscribes to an event.
| callback | Function | Yes| Callback invoked when the event is triggered.| | callback | Function | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
```ts
import Ability from '@ohos.application.Ability';
export default class MainAbility extends Ability {
onForeground() {
this.context.eventHub.on('123', this.func1);
this.context.eventHub.on('123', () => {
console.log('call anonymous func 1');
});
// Result
// func1 is called
// call anonymous func 1
this.context.eventHub.emit('123');
}
func1() {
console.log('func1 is called');
}
}
```
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onForeground() {
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
// eventFunc is called
// call anonymous eventFunc
this.context.eventHub.emit("myEvent");
}
eventFunc() {
console.log("eventFunc is called");
}
}
```
## EventHub.off ## EventHub.off
off(event: string, callback?: Function): void; off(event: string, callback?: Function): void;
Unsubscribes from an 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 **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -82,28 +77,27 @@ Unsubscribes from an event. ...@@ -82,28 +77,27 @@ Unsubscribes from an event.
| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.| | callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.|
**Example** **Example**
```ts
import Ability from '@ohos.application.Ability';
export default class MainAbility extends Ability {
onForeground() {
this.context.eventHub.on('123', this.func1);
this.context.eventHub.off('123', this.func1); // Unsubscribe from the myEvent event with the callback eventFunc1.
this.context.eventHub.on('123', this.func1);
this.context.eventHub.on('123', this.func2);
this.context.eventHub.off('123'); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2).
}
func1() {
console.log('func1 is called');
}
func2() {
console.log('func2 is called');
}
}
```
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onForeground() {
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 ## EventHub.emit
...@@ -121,26 +115,25 @@ Triggers an event. ...@@ -121,26 +115,25 @@ Triggers an event.
| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.|
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.application.Ability';
export default class EntryAbility extends UIAbility { export default class MainAbility extends Ability {
onForeground() { onForeground() {
this.context.eventHub.on("myEvent", this.eventFunc); this.context.eventHub.on('123', this.func1);
// Result // Result
// eventFunc is called,undefined,undefined // func1 is called,undefined,undefined
this.context.eventHub.emit("myEvent"); this.context.eventHub.emit('123');
// Result // Result
// eventFunc is called,1,undefined // func1 is called,1,undefined
this.context.eventHub.emit("myEvent", 1); this.context.eventHub.emit('123', 1);
// Result // Result
// eventFunc is called,1,2 // func1 is called,1,2
this.context.eventHub.emit("myEvent", 1, 2); this.context.eventHub.emit('123', 1, 2);
} }
func1(a, b) {
eventFunc(argOne, argTwo) { console.log('func1 is called,' + a + ',' + b);
console.log("eventFunc is called," + argOne + "," + argTwo); }
} }
} ```
```
...@@ -31,8 +31,8 @@ To adapt to devices with different performance, an application provides three mo ...@@ -31,8 +31,8 @@ To adapt to devices with different performance, an application provides three mo
Define a **ServiceExtension** with the same name for the three modules. Define a **ServiceExtension** with the same name for the three modules.
```ts ```ts
import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility';
import Want from '@ohos.application.Want' import Want from '@ohos.application.Want';
export default class TheServiceExtension extends ServiceExtension { export default class TheServiceExtension extends ServiceExtension {
onCreate(want:Want) { onCreate(want:Want) {
console.log('ServiceAbility onCreate, want: ' + want.abilityName); console.log('ServiceAbility onCreate, want: ' + want.abilityName);
...@@ -61,15 +61,14 @@ export default class TheServiceExtension extends ServiceExtension { ...@@ -61,15 +61,14 @@ export default class TheServiceExtension extends ServiceExtension {
Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import Ability from '@ohos.app.ability.Ability';
export default class MainAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate"); console.log('[Demo] MainAbility onCreate');
let wantExt = { let wantExt = {
deviceId: "", deviceId: '',
bundleName: "com.example.TheServiceExtension", bundleName: 'com.example.TheServiceExtension',
abilityName: "TheServiceExtension", abilityName: 'TheServiceExtension',
}; };
this.context.startServiceExtensionAbility(wantExt); this.context.startServiceExtensionAbility(wantExt);
} }
...@@ -84,29 +83,29 @@ export default class ServiceModel { ...@@ -84,29 +83,29 @@ export default class ServiceModel {
constructor() {} constructor() {}
executeTask() { executeTask() {
if (globalThis.ExtensionContext == undefined) { if (globalThis.ExtensionContext === undefined) {
console.log("ERROR, ServiceExtension does not exist"); console.log('ERROR, ServiceExtension does not exist');
return; return;
} }
var moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; let moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo;
this.moduleName = moduleInfo.name; this.moduleName = moduleInfo.name;
// Execute service logic based on the module name, which differentiates devices with different performance. // Execute service logic based on the module name, which differentiates devices with different performance.
switch (this.moduleName) { switch (this.moduleName) {
case "highPerformance": case 'highPerformance':
console.log("This is high performance device."); console.log('This is high performance device.');
// Execute the corresponding service logic. // Execute the corresponding service logic.
break; break;
case "midPerformance": case 'midPerformance':
console.log("This is mid performance device."); console.log('This is mid performance device.');
// Execute the corresponding service logic. // Execute the corresponding service logic.
break; break;
case "lowPerformance": case 'lowPerformance':
console.log("This is low performance device."); console.log('This is low performance device.');
// Execute the corresponding service logic. // Execute the corresponding service logic.
break; break;
default: default:
console.log("ERROR, invalid moduleName."); console.log('ERROR, invalid moduleName.');
break; break;
} }
} }
......
...@@ -5,7 +5,7 @@ The **ExtensionRunningInfo** module encapsulates ExtensionAbility running inform ...@@ -5,7 +5,7 @@ The **ExtensionRunningInfo** module encapsulates ExtensionAbility running inform
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - This module is marked as @systemapi and not visible to third-party applications. > - The APIs of this module are system APIs and cannot be called by third-party applications.
## Usage ## Usage
...@@ -17,37 +17,29 @@ Import the **abilityManager** module and obtain the ExtensionAbility running inf ...@@ -17,37 +17,29 @@ Import the **abilityManager** module and obtain the ExtensionAbility running inf
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.| | extension | ElementName | Yes| No| ExtensionAbility information.|
| pid | number | Yes| No| Process ID.| | pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| UID of the application.| | uid | number | Yes| No| UID of the application.|
| processName | string | Yes| No| Process name.| | processName | string | Yes| No| Process name.|
| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| | startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.|
| clientPackage | Array&lt;String&gt; | Yes| No| Names of all packages in the process.| | clientPackage | Array&lt;String&gt; | Yes| No| Names of all packages in the process.|
| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.| | type | [bundle.ExtensionAbilityType](js-apis-Bundle.md) | Yes| No| ExtensionAbility type.|
**Example** **Example**
```ts ```ts
import abilityManager from '@ohos.app.ability.abilityManager' import abilityManager from '@ohos.application.abilityManager';
let upperLimit = 1;
var upperLimit = 1; abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
function getExtensionInfos() { console.log('getExtensionRunningInfos err: ' + err + ' data: ' + JSON.stringify(data));
abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { for (let i = 0; i < data.length; i++) {
if (error && error.code) { let extensionRunningInfo = data[i];
console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + console.log('extensionRunningInfo.extension: ' + JSON.stringify(extensionRunningInfo.extension));
' error.message: ' + JSON.stringify(error.message)); console.log('extensionRunningInfo.pid: ' + JSON.stringify(extensionRunningInfo.pid));
return; console.log('extensionRunningInfo.uid: ' + JSON.stringify(extensionRunningInfo.uid));
} console.log('extensionRunningInfo.processName: ' + JSON.stringify(extensionRunningInfo.processName));
console.log('extensionRunningInfo.startTime: ' + JSON.stringify(extensionRunningInfo.startTime));
for (let i = 0; i < data.length; i++) { console.log('extensionRunningInfo.clientPackage: ' + JSON.stringify(extensionRunningInfo.clientPackage));
let extensionRunningInfo = data[i]; console.log('extensionRunningInfo.type: ' + JSON.stringify(extensionRunningInfo.type));
console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); }
console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); });
console.log("extensionRunningInfo.uid: " + JSON.stringify(extensionRunningInfo.uid));
console.log("extensionRunningInfo.processName: " + JSON.stringify(extensionRunningInfo.processName));
console.log("extensionRunningInfo.startTime: " + JSON.stringify(extensionRunningInfo.startTime));
console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage));
console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type));
}
});
}
``` ```
...@@ -16,19 +16,18 @@ Before using the **ServiceExtensionContext** module, you must first obtain a **F ...@@ -16,19 +16,18 @@ Before using the **ServiceExtensionContext** module, you must first obtain a **F
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) { onAddForm() {
let formContext = this.context; // Obtain a FormExtensionContext instance. let formContext = this.context; // »ñÈ¡FormExtensionContext
// ... // ...
let dataObj1 = { let dataObj1 = {
temperature: "11c", temperature:'11c',
"time": "11:00" 'time':'11:00'
}; };
let obj1 = formBindingData.createFormBindingData(dataObj1); let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1; return obj1;
} }
}; }
``` ```
## startAbility ## startAbility
...@@ -51,29 +50,23 @@ Starts an ability. This API uses an asynchronous callback to return the result. ...@@ -51,29 +50,23 @@ Starts an ability. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; let want = {
deviceId: '',
export default class MyFormExtensionAbility extends FormExtensionAbility { bundleName: 'com.example.formstartability',
onFormEvent(formId, message) { abilityName: 'MainAbility',
// Call startAbility() when the message event is triggered. action: 'action1',
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); entities: ['entity1'],
let want = { type: 'MIMETYPE',
deviceId: "", uri: 'key={true,true,false}',
bundleName: "com.example.formstartability", parameters: {}
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');
}
});
}
}; };
this.context.startAbility(want, (error, data) => {
if (error) {
console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error));
} else {
console.log(`FormExtensionContext startAbility success`);
}
});
``` ```
## startAbility ## startAbility
...@@ -96,30 +89,24 @@ Starts an ability. This API uses a promise to return the result. ...@@ -96,30 +89,24 @@ Starts an ability. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------ | ---------------------------------- | | ------------ | ---------------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&lt; | Promise that returns no value.|
**Example** **Example**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; let want = {
deviceId: '',
export default class MyFormExtensionAbility extends FormExtensionAbility { bundleName: 'com.example.formstartability',
onFormEvent(formId, message) { abilityName: 'MainAbility',
// Call startAbility() when the message event is triggered. action: 'action1',
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); entities: ['entity1'],
let want = { type: 'MIMETYPE',
deviceId: "", uri: 'key={true,true,false}',
bundleName: "com.example.formstartability", parameters: {}
abilityName: "EntryAbility",
parameters: {
"message": message
}
};
this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
console.info("StartAbility failed");
});
}
}; };
this.context.startAbility(want).then(() => {
console.info('StartAbility Success');
}).catch((error) => {
console.info('StartAbility failed');
});
``` ```
...@@ -15,19 +15,19 @@ The **MissionCallback** module defines the callbacks invoked after synchronizati ...@@ -15,19 +15,19 @@ The **MissionCallback** module defines the callbacks invoked after synchronizati
import distributedMissionManager from '@ohos.distributedMissionManager'; import distributedMissionManager from '@ohos.distributedMissionManager';
let missionDeviceInfo = { let missionDeviceInfo = {
deviceId: "123456" deviceId: '123456'
}; };
let missionCallback = { let missionCallback = {
notifyMissionsChanged: function (deviceId) { notifyMissionsChanged: function (deviceId) {
console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); console.log('notifyMissionsChanged deviceId: ' + JSON.stringify(deviceId));
}, },
notifySnapshot: function (deviceId, mission) { notifySnapshot: function (deviceId, mission) {
console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); console.log('notifySnapshot deviceId: ' + JSON.stringify(deviceId));
console.log("notifySnapshot mission: " + JSON.stringify(mission)); console.log('notifySnapshot mission: ' + JSON.stringify(mission));
}, },
notifyNetDisconnect: function (deviceId, state) { notifyNetDisconnect: function (deviceId, state) {
console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); console.log('notifyNetDisconnect deviceId: ' + JSON.stringify(deviceId));
console.log("notifyNetDisconnect state: " + JSON.stringify(state)); console.log('notifyNetDisconnect state: ' + JSON.stringify(state));
} }
}; };
distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback);
......
...@@ -13,19 +13,19 @@ The **MissionDeviceInfo** module defines the parameters required for registering ...@@ -13,19 +13,19 @@ The **MissionDeviceInfo** module defines the parameters required for registering
import distributedMissionManager from '@ohos.distributedMissionManager'; import distributedMissionManager from '@ohos.distributedMissionManager';
let missionDeviceInfo = { let missionDeviceInfo = {
deviceId: "123456" deviceId: '123456'
}; };
let missionCallback = { let missionCallback = {
notifyMissionsChanged: function (deviceId) { notifyMissionsChanged: function (deviceId) {
console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); console.log('notifyMissionsChanged deviceId: ' + JSON.stringify(deviceId));
}, },
notifySnapshot: function (mission, deviceId) { notifySnapshot: function (mission, deviceId) {
console.log("notifySnapshot mission: " + JSON.stringify(mission)); console.log('notifySnapshot mission: ' + JSON.stringify(mission));
console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); console.log('notifySnapshot deviceId: ' + JSON.stringify(deviceId));
}, },
notifyNetDisconnect: function (mission, state) { notifyNetDisconnect: function (mission, state) {
console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); console.log('notifyNetDisconnect mission: ' + JSON.stringify(mission));
console.log("notifyNetDisconnect state: " + JSON.stringify(state)); console.log('notifyNetDisconnect state: ' + JSON.stringify(state));
} }
}; };
distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback);
......
...@@ -19,27 +19,16 @@ The **MissionInfo** module defines detailed information about a mission. The inf ...@@ -19,27 +19,16 @@ The **MissionInfo** module defines detailed information about a mission. The inf
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.application.missionManager';
try { missionManager.getMissionInfo('12345', 1, (error, data) => {
missionManager.getMissionInfo("", 1, (error, data) => { console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId));
if (error.code) { console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState));
// Process service logic errors. console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState));
console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp));
"error.message:" + JSON.stringify(error.message)); console.info('getMissionInfo want is:' + JSON.stringify(data.want));
return; 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));
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);
}
``` ```
# MissionListener # MissionListener
The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [on](js-apis-app-ability-missionManager.md#missionmanageron). The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [registerMissionListener](js-apis-application-missionManager.md#missionmanagerregistermissionlistener).
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
...@@ -16,32 +16,27 @@ The **MissionListener** module defines the listeners used to observe the mission ...@@ -16,32 +16,27 @@ The **MissionListener** module defines the listeners used to observe the mission
**Example** **Example**
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.application.missionManager';
let listener = { let listener = {
onMissionCreated: function (mission) { onMissionCreated: function (mission) {
console.log("onMissionCreated mission: " + JSON.stringify(mission)); console.log('onMissionCreated mission: ' + JSON.stringify(mission));
}, },
onMissionDestroyed: function (mission) { onMissionDestroyed: function (mission) {
console.log("onMissionDestroyed mission: " + JSON.stringify(mission)); console.log('onMissionDestroyed mission: ' + JSON.stringify(mission));
}, },
onMissionSnapshotChanged: function (mission) { onMissionSnapshotChanged: function (mission) {
console.log("onMissionSnapshotChanged mission: " + JSON.stringify(mission)); console.log('onMissionSnapshotChanged mission: ' + JSON.stringify(mission));
}, },
onMissionMovedToFront: function (mission) { onMissionMovedToFront: function (mission) {
console.log("onMissionMovedToFront mission: " + JSON.stringify(mission)); console.log('onMissionMovedToFront mission: ' + JSON.stringify(mission));
}, },
onMissionIconUpdated: function (mission, icon) { onMissionIconUpdated: function (mission, icon) {
console.log("onMissionIconUpdated mission: " + JSON.stringify(mission)); console.log('onMissionIconUpdated mission: ' + JSON.stringify(mission));
}, },
onMissionClosed: function (mission) { onMissionClosed: function (mission) {
console.log("onMissionClosed mission: " + JSON.stringify(mission)); console.log('onMissionClosed mission: ' + JSON.stringify(mission));
} }
}; };
let listenerid = missionManager.registerMissionListener(listener);
try {
let listenerId = missionManager.on("mission", listener);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
``` ```
...@@ -15,14 +15,14 @@ The **MissionParameter** module defines the parameters required for mission sync ...@@ -15,14 +15,14 @@ The **MissionParameter** module defines the parameters required for mission sync
import distributedMissionManager from '@ohos.distributedMissionManager'; import distributedMissionManager from '@ohos.distributedMissionManager';
let missionParameter = { let missionParameter = {
deviceId: "123456", deviceId: '123456',
fixConflict: true, fixConflict: true,
tag: 123 tag: 123
}; };
try { try {
distributedMissionManager.startSyncRemoteMissions(missionParameter, distributedMissionManager.startSyncRemoteMissions(missionParameter,
(err, data) => { (err, data) => {
console.log("startSyncRemoteMissions, data: " + JSON.stringify(data)); console.log('startSyncRemoteMissions, data: ' + JSON.stringify(data));
} }
); );
} catch (err) { } catch (err) {
......
...@@ -20,33 +20,19 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** ...@@ -20,33 +20,19 @@ The mission snapshot information can be obtained by using **getMissionSnapShot**
**Example** **Example**
```ts ```ts
import ElementName from '@ohos.bundle'; import ElementName from '@ohos.bundle';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import missionManager from '@ohos.app.ability.missionManager'; import missionManager from '@ohos.application.missionManager';
try { missionManager.getMissionInfos('', 10, (error, missions) => {
missionManager.getMissionInfos("", 10, (error, missions) => { console.log('getMissionInfos is called, error.code = ' + error.code);
if (error.code) { console.log('size = ' + missions.length);
console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + console.log('missions = ' + JSON.stringify(missions));
"error.message:" + JSON.stringify(error.message)); let id = missions[0].missionId;
return;
} missionManager.getMissionSnapShot('', id, (error, snapshot) => {
console.log("size = " + missions.length); console.log('getMissionSnapShot is called, error.code = ' + error.code);
console.log("missions = " + JSON.stringify(missions)); console.log('bundleName = ' + snapshot.ability.bundleName);
var id = missions[0].missionId; });
});
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);
}
``` ```
...@@ -17,7 +17,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla ...@@ -17,7 +17,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
let context = undefined; let context = undefined;
class EntryAbility extends ServiceExtensionAbility { class MainAbility extends ServiceExtensionAbility {
onCreate() { onCreate() {
context = this.context; // Obtain a ServiceExtensionContext instance. context = this.context; // Obtain a ServiceExtensionContext instance.
} }
...@@ -68,9 +68,9 @@ Starts an ability. This API uses an asynchronous callback to return the result. ...@@ -68,9 +68,9 @@ Starts an ability. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
try { try {
...@@ -141,11 +141,11 @@ Starts an ability. This API uses a promise to return the result. ...@@ -141,11 +141,11 @@ Starts an ability. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -212,12 +212,12 @@ Starts an ability with the start options specified. This API uses an asynchronou ...@@ -212,12 +212,12 @@ Starts an ability with the start options specified. This API uses an asynchronou
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -247,7 +247,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ...@@ -247,7 +247,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
Observe the following when using this API: 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 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. - If **visible** of the target ability is **false**, 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). - 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 capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -290,12 +290,12 @@ Observe the following when using this API: ...@@ -290,12 +290,12 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startAbilityWithAccount(want, accountId, (error) => { this.context.startAbilityWithAccount(want, accountId, (error) => {
...@@ -323,7 +323,7 @@ Starts an ability with the account ID and start options specified. This API uses ...@@ -323,7 +323,7 @@ Starts an ability with the account ID and start options specified. This API uses
Observe the following when using this API: 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 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. - If **visible** of the target ability is **false**, 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). - 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 capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -367,13 +367,13 @@ Observe the following when using this API: ...@@ -367,13 +367,13 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -404,7 +404,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -404,7 +404,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu
Observe the following when using this API: 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 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. - If **visible** of the target ability is **false**, 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). - 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 capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -453,13 +453,13 @@ Observe the following when using this API: ...@@ -453,13 +453,13 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -518,10 +518,10 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to ...@@ -518,10 +518,10 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -584,10 +584,10 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu ...@@ -584,10 +584,10 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -614,7 +614,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: ...@@ -614,7 +614,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
Starts a new ServiceExtensionAbility 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 only when the account ID is not the current user) **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -650,12 +650,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use ...@@ -650,12 +650,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -681,7 +681,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ ...@@ -681,7 +681,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
Starts a new ServiceExtensionAbility 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 only when the account ID is not the current user) **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -721,12 +721,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use ...@@ -721,12 +721,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId) this.context.startServiceExtensionAbilityWithAccount(want, accountId)
...@@ -780,10 +780,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch ...@@ -780,10 +780,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -843,10 +843,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise ...@@ -843,10 +843,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -873,7 +873,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: ...@@ -873,7 +873,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
Stops a ServiceExtensionAbility 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 only when the account ID is not the current user) **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -905,12 +905,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec ...@@ -905,12 +905,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -936,7 +936,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< ...@@ -936,7 +936,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
Stops a ServiceExtensionAbility 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 only when the account ID is not the current user) **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -973,12 +973,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec ...@@ -973,12 +973,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId) this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
...@@ -1118,17 +1118,17 @@ Connects this ability to a ServiceAbility. ...@@ -1118,17 +1118,17 @@ Connects this ability to a ServiceAbility.
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} };
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbility(want, options); connection = this.context.connectServiceExtensionAbility(want, options);
} catch (paramError) { } catch (paramError) {
...@@ -1178,19 +1178,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect ...@@ -1178,19 +1178,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.example.myapplication", bundleName: 'com.extreme.test',
abilityName: "EntryAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} }
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options);
} catch (paramError) { } catch (paramError) {
...@@ -1214,7 +1214,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous ...@@ -1214,7 +1214,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.| | connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.|
| callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | No| Callback used to return the result.|
**Error codes** **Error codes**
...@@ -1232,7 +1232,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous ...@@ -1232,7 +1232,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous
```ts ```ts
// connection is the return value of connectServiceExtensionAbility. // connection is the return value of connectServiceExtensionAbility.
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection, (error) => { this.context.disconnectServiceExtensionAbility(connection, (error) => {
...@@ -1266,7 +1266,7 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret ...@@ -1266,7 +1266,7 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| connection | number | Yes| Number returned after **connectAbility** is called.| | connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.|
**Return value** **Return value**
...@@ -1288,8 +1288,8 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret ...@@ -1288,8 +1288,8 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret
**Example** **Example**
```ts ```ts
// connection is the return value of connectAbility. // connection is the return value of connectServiceExtensionAbility.
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection) this.context.disconnectServiceExtensionAbility(connection)
...@@ -1317,8 +1317,8 @@ Starts an ability in the foreground or background and obtains the caller object ...@@ -1317,8 +1317,8 @@ Starts an ability in the foreground or background and obtains the caller object
Observe the following when using this API: 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 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. - If **visible** of the target ability is **false**, 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). - 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 capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -1355,14 +1355,14 @@ Observe the following when using this API: ...@@ -1355,14 +1355,14 @@ Observe the following when using this API:
Start an ability in the background. Start an ability in the background.
```ts ```ts
var caller = undefined; let caller = undefined;
// Start an ability in the background by not passing parameters. // Start an ability in the background by not passing parameters.
var wantBackground = { let wantBackground = {
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
moduleName: "entry", moduleName: 'entry',
abilityName: "EntryAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}; };
try { try {
...@@ -1386,16 +1386,16 @@ Observe the following when using this API: ...@@ -1386,16 +1386,16 @@ Observe the following when using this API:
Start an ability in the foreground. Start an ability in the foreground.
```ts ```ts
var caller = undefined; let caller = undefined;
// Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true.
var wantForeground = { let wantForeground = {
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
moduleName: "entry", moduleName: 'entry',
abilityName: "EntryAbility", abilityName: 'MainAbility',
deviceId: "", deviceId: '',
parameters: { parameters: {
"ohos.aafwk.param.callAbilityToForeground": true 'ohos.aafwk.param.callAbilityToForeground': true
} }
}; };
......
...@@ -19,13 +19,13 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio ...@@ -19,13 +19,13 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
let abilityDelegator; let abilityDelegator;
let cmd = "cmd"; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => {
console.info("executeShellCommand callback, result: ", err); console.info('executeShellCommand callback, failed: ', err);
console.info("executeShellCommand callback, data: ", data); console.info('executeShellCommand callback, success: ', data);
}); });
``` ```
...@@ -66,9 +66,9 @@ Observe the following when using this API: ...@@ -66,9 +66,9 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
try { try {
...@@ -138,12 +138,12 @@ Observe the following when using this API: ...@@ -138,12 +138,12 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -218,11 +218,11 @@ Observe the following when using this API: ...@@ -218,11 +218,11 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -295,10 +295,10 @@ Observe the following when using this API: ...@@ -295,10 +295,10 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -310,7 +310,7 @@ Observe the following when using this API: ...@@ -310,7 +310,7 @@ Observe the following when using this API:
return; return;
} }
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResult succeed, result.resultCode = " + console.log('startAbilityForResult succeed, result.resultCode = ' +
result.resultCode) result.resultCode)
}); });
} catch (paramError) { } catch (paramError) {
...@@ -371,12 +371,12 @@ Observe the following when using this API: ...@@ -371,12 +371,12 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -389,7 +389,7 @@ Observe the following when using this API: ...@@ -389,7 +389,7 @@ Observe the following when using this API:
return; return;
} }
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResult succeed, result.resultCode = " + console.log('startAbilityForResult succeed, result.resultCode = ' +
result.resultCode) result.resultCode)
}); });
} catch (paramError) { } catch (paramError) {
...@@ -457,11 +457,11 @@ Observe the following when using this API: ...@@ -457,11 +457,11 @@ Observe the following when using this API:
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.example.myapp", bundleName: 'com.example.myapp',
abilityName: "MyAbility" abilityName: 'MyAbility'
}; };
var options = { let options = {
windowMode: 0, windowMode: 0,
}; };
...@@ -469,7 +469,7 @@ Observe the following when using this API: ...@@ -469,7 +469,7 @@ Observe the following when using this API:
this.context.startAbilityForResult(want, options) this.context.startAbilityForResult(want, options)
.then((result) => { .then((result) => {
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); console.log('startAbilityForResult succeed, result.resultCode = ' + result.resultCode);
}) })
.catch((error) => { .catch((error) => {
// Process service logic errors. // Process service logic errors.
...@@ -531,12 +531,12 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ...@@ -531,12 +531,12 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => {
...@@ -547,7 +547,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ...@@ -547,7 +547,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
return; return;
} }
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' +
result.resultCode) result.resultCode)
}); });
} catch (paramError) { } catch (paramError) {
...@@ -607,13 +607,13 @@ Starts an ability with the start options and account ID specified. This API uses ...@@ -607,13 +607,13 @@ Starts an ability with the start options and account ID specified. This API uses
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -626,7 +626,7 @@ Starts an ability with the start options and account ID specified. This API uses ...@@ -626,7 +626,7 @@ Starts an ability with the start options and account ID specified. This API uses
return; return;
} }
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' +
result.resultCode) result.resultCode)
}); });
} catch (paramError) { } catch (paramError) {
...@@ -691,13 +691,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -691,13 +691,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -705,7 +705,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -705,7 +705,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu
this.context.startAbilityForResultWithAccount(want, accountId, options) this.context.startAbilityForResultWithAccount(want, accountId, options)
.then((result) => { .then((result) => {
// Carry out normal service processing. // Carry out normal service processing.
console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' +
result.resultCode) result.resultCode)
}) })
.catch((error) => { .catch((error) => {
...@@ -756,10 +756,10 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu ...@@ -756,10 +756,10 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -816,10 +816,10 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result. ...@@ -816,10 +816,10 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -877,12 +877,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an ...@@ -877,12 +877,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -942,12 +942,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a ...@@ -942,12 +942,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startServiceExtensionAbilityWithAccount(want, accountId) this.context.startServiceExtensionAbilityWithAccount(want, accountId)
...@@ -1000,10 +1000,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch ...@@ -1000,10 +1000,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -1057,10 +1057,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise ...@@ -1057,10 +1057,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
try { try {
...@@ -1119,12 +1119,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic ...@@ -1119,12 +1119,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => {
...@@ -1181,12 +1181,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic ...@@ -1181,12 +1181,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.stopServiceExtensionAbilityWithAccount(want, accountId) this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
...@@ -1315,13 +1315,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe ...@@ -1315,13 +1315,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.extreme.myapplication", bundleName: 'com.extreme.myapplication',
abilityName: "SecondAbility" abilityName: 'SecondAbility'
} }
var resultCode = 100; let resultCode = 100;
// AbilityResult information returned to the caller. // AbilityResult information returned to the caller.
var abilityResult = { let abilityResult = {
want, want,
resultCode resultCode
} }
...@@ -1380,13 +1380,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe ...@@ -1380,13 +1380,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe
**Example** **Example**
```ts ```ts
var want = { let want = {
bundleName: "com.extreme.myapplication", bundleName: 'com.extreme.myapplication',
abilityName: "SecondAbility" abilityName: 'SecondAbility'
} }
var resultCode = 100; let resultCode = 100;
// AbilityResult information returned to the caller. // AbilityResult information returned to the caller.
var abilityResult = { let abilityResult = {
want, want,
resultCode resultCode
} }
...@@ -1445,18 +1445,18 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV ...@@ -1445,18 +1445,18 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} }
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbility(want, options); connection = this.context.connectServiceExtensionAbility(want, options);
} catch (paramError) { } catch (paramError) {
...@@ -1509,19 +1509,19 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV ...@@ -1509,19 +1509,19 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onConnect(elementName, remote) { console.log('----------- onConnect -----------') },
onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') },
onFailed(code) { console.log('----------- onFailed -----------') } onFailed(code) { console.log('----------- onFailed -----------') }
} }
var connection = null; let connection = null;
try { try {
connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options);
} catch (paramError) { } catch (paramError) {
...@@ -1568,7 +1568,7 @@ Disconnects a connection. This API uses a promise to return the result. ...@@ -1568,7 +1568,7 @@ Disconnects a connection. This API uses a promise to return the result.
```ts ```ts
// connection is the return value of connectServiceExtensionAbility. // connection is the return value of connectServiceExtensionAbility.
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection) this.context.disconnectServiceExtensionAbility(connection)
...@@ -1620,7 +1620,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r ...@@ -1620,7 +1620,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
```ts ```ts
// connection is the return value of connectServiceExtensionAbility. // connection is the return value of connectServiceExtensionAbility.
var connection = 1; let connection = 1;
try { try {
this.context.disconnectServiceExtensionAbility(connection, (error) => { this.context.disconnectServiceExtensionAbility(connection, (error) => {
...@@ -1670,14 +1670,14 @@ Observe the following when using this API: ...@@ -1670,14 +1670,14 @@ Observe the following when using this API:
Start an ability in the background. Start an ability in the background.
```ts ```ts
var caller = undefined; let caller = undefined;
// Start an ability in the background by not passing parameters. // Start an ability in the background by not passing parameters.
var wantBackground = { let wantBackground = {
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
moduleName: "entry", moduleName: 'entry',
abilityName: "MainAbility", abilityName: 'MainAbility',
deviceId: "" deviceId: ''
}; };
try { try {
...@@ -1701,16 +1701,16 @@ Observe the following when using this API: ...@@ -1701,16 +1701,16 @@ Observe the following when using this API:
Start an ability in the foreground. Start an ability in the foreground.
```ts ```ts
var caller = undefined; let caller = undefined;
// Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true.
var wantForeground = { let wantForeground = {
bundleName: "com.example.myservice", bundleName: 'com.example.myservice',
moduleName: "entry", moduleName: 'entry',
abilityName: "MainAbility", abilityName: 'MainAbility',
deviceId: "", deviceId: '',
parameters: { parameters: {
"ohos.aafwk.param.callAbilityToForeground": true 'ohos.aafwk.param.callAbilityToForeground': true
} }
}; };
...@@ -1780,12 +1780,12 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ...@@ -1780,12 +1780,12 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
try { try {
this.context.startAbilityWithAccount(want, accountId, (error) => { this.context.startAbilityWithAccount(want, accountId, (error) => {
...@@ -1855,13 +1855,13 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ...@@ -1855,13 +1855,13 @@ Starts an ability with the account ID specified. This API uses an asynchronous c
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -1932,13 +1932,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -1932,13 +1932,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu
**Example** **Example**
```ts ```ts
var want = { let want = {
deviceId: "", deviceId: '',
bundleName: "com.extreme.test", bundleName: 'com.extreme.test',
abilityName: "MainAbility" abilityName: 'MainAbility'
}; };
var accountId = 100; let accountId = 100;
var options = { let options = {
windowMode: 0 windowMode: 0
}; };
...@@ -1978,7 +1978,7 @@ Requests permissions from the user by displaying a dialog box. This API uses an ...@@ -1978,7 +1978,7 @@ Requests permissions from the user by displaying a dialog box. This API uses an
**Example** **Example**
```ts ```ts
var permissions=['com.example.permission'] let permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(result) => { this.context.requestPermissionsFromUser(permissions,(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
}); });
...@@ -2009,7 +2009,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p ...@@ -2009,7 +2009,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p
**Example** **Example**
```ts ```ts
var permissions=['com.example.permission'] let permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions).then((data) => { this.context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success:' + JSON.stringify(data)); console.log('success:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
...@@ -2037,7 +2037,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ...@@ -2037,7 +2037,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call
**Example** **Example**
```ts ```ts
this.context.setMissionLabel("test",(result) => { this.context.setMissionLabel('test',(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
}); });
``` ```
...@@ -2066,7 +2066,7 @@ Sets a label for this ability in the mission. This API uses a promise to return ...@@ -2066,7 +2066,7 @@ Sets a label for this ability in the mission. This API uses a promise to return
**Example** **Example**
```ts ```ts
this.context.setMissionLabel("test").then(() => { this.context.setMissionLabel('test').then(() => {
console.log('success'); console.log('success');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
...@@ -2093,9 +2093,9 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call ...@@ -2093,9 +2093,9 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
```ts ```ts
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
var imagePixelMap; let imagePixelMap;
var color = new ArrayBuffer(0); let color = new ArrayBuffer(0);
var initializationOptions = { let initializationOptions = {
size: { size: {
height: 100, height: 100,
width: 100 width: 100
...@@ -2140,9 +2140,9 @@ Sets an icon for this ability in the mission. This API uses a promise to return ...@@ -2140,9 +2140,9 @@ Sets an icon for this ability in the mission. This API uses a promise to return
```ts ```ts
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
var imagePixelMap; let imagePixelMap;
var color = new ArrayBuffer(0); let color = new ArrayBuffer(0);
var initializationOptions = { let initializationOptions = {
size: { size: {
height: 100, height: 100,
width: 100 width: 100
...@@ -2180,7 +2180,7 @@ Restores the window stage data for this ability. ...@@ -2180,7 +2180,7 @@ Restores the window stage data for this ability.
**Example** **Example**
```ts ```ts
var storage = new LocalStorage(); let storage = new LocalStorage();
this.context.restoreWindowStage(storage); this.context.restoreWindowStage(storage);
``` ```
...@@ -2201,6 +2201,6 @@ Checks whether this ability is in the terminating state. ...@@ -2201,6 +2201,6 @@ Checks whether this ability is in the terminating state.
**Example** **Example**
```ts ```ts
var isTerminating = this.context.isTerminating(); let isTerminating = this.context.isTerminating();
console.log('ability state :' + isTerminating); console.log('ability state :' + isTerminating);
``` ```
# WindowExtensionContext
The **WindowExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WindowExtensionAbility.
The **WindowExtensionContext** module provides the capabilities of the [WindowExtensionAbility](js-apis-application-windowExtensionAbility.md), including starting the ability.
> **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.
>
> - The APIs of this module can be used only in the stage model.
## Usage
Before using the **WindowExtensionContext** module, you must define a child class that inherits from **WindowExtensionAbility**.
```ts
import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
let context;
class WindowExtAbility extends WindowExtensionAbility {
onConnect() {
context = this.context; // Obtain a WindowExtensionContext instance.
}
}
```
## WindowExtensionContext.startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void
Starts an ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.|
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'MainAbility'
};
let options = {
windowMode: 102
};
try {
this.context.startAbility(want, options, (error) => {
if (error.code) {
// Process service logic errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
return;
}
// Carry out normal service processing.
console.log('startAbility succeed');
});
} catch (paramError) {
// Process input parameter errors.
console.error('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## WindowExtensionContext.startAbility
startAbility(want: Want, options?: StartOptions): Promise\<void>
Starts an ability. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**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) | No| Parameters used for starting the ability.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```ts
let want = {
bundleName: 'com.example.myapp',
abilityName: 'MainAbility'
};
let options = {
windowMode: 102,
};
try {
this.context.startAbility(want, options)
.then((data) => {
// Carry out normal service processing.
console.log('startAbility succeed');
})
.catch((error) => {
// Process service logic errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
});
} catch (paramError) {
// Process input parameter errors.
console.error('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
...@@ -6,7 +6,7 @@ The **TriggerInfo** module defines the information required for triggering the W ...@@ -6,7 +6,7 @@ The **TriggerInfo** module defines the information required for triggering the W
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | --- |-------------------- | ----------- | | ---------- | --- |-------------------- | ----------- |
| code | number | Yes | Custom result code provided for the target WantAgent.| | code | number | Yes | Result code.|
| want | Want | No | Want. | | want | Want | No | Want. |
| permission | string | No | Permission. | | permission | string | No | Permission. |
| extraInfo | {[key: string]: any} | No | Extra information. | | extraInfo | {[key: string]: any} | No | Extra information. |
...@@ -7,7 +7,7 @@ The **WantAgentInfo** module defines the information required for triggering a * ...@@ -7,7 +7,7 @@ The **WantAgentInfo** module defines the information required for triggering a *
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------- | ------------------------------- | ---- | ---------------------- | | -------------- | ------------------------------- | ---- | ---------------------- |
| wants | Array\<Want\> | Yes | Array of all **Want** objects. | | wants | Array\<Want\> | Yes | Array of all **Want** objects. |
| operationType | wantAgent.OperationType | Yes | Operation type. | | operationType | [wantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | Yes | Operation type. |
| requestCode | number | Yes | Request code defined by the user.| | requestCode | number | Yes | Request code defined by the user.|
| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-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. | | extraInfo | {[key: string]: any} | No | Extra information. |
# @ohos.wantAgent (wantAgent) # @ohos.wantAgent (WantAgent)
The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object.
...@@ -16,7 +16,7 @@ import WantAgent from '@ohos.wantAgent'; ...@@ -16,7 +16,7 @@ import WantAgent from '@ohos.wantAgent';
getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>): void getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>): void
Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -75,7 +75,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); ...@@ -75,7 +75,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
getWantAgent(info: WantAgentInfo): Promise\<WantAgent\> getWantAgent(info: WantAgentInfo): Promise\<WantAgent\>
Obtains a **WantAgent** object. This API uses a promise to return the result. Obtains a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -160,8 +160,15 @@ function getWantAgentCallback(err, data) { ...@@ -160,8 +160,15 @@ function getWantAgentCallback(err, data) {
if (err.code == 0) { if (err.code == 0) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('----getWantAgent failed!----'); console.error('getWantAgent failed, error: ' + JSON.stringify(err));
return;
} }
// getBundleName callback
function getBundleNameCallback(err, data) {
console.info('==========================>getBundleNameCallback=======================>');
}
WantAgent.getBundleName(wantAgent, getBundleNameCallback);
} }
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -192,12 +199,6 @@ let wantAgentInfo = { ...@@ -192,12 +199,6 @@ let wantAgentInfo = {
} }
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
// getBundleName callback
function getBundleNameCallback(err, data) {
console.info('==========================>getBundleNameCallback=======================>');
}
WantAgent.getBundleName(wantAgent, getBundleNameCallback);
``` ```
...@@ -261,10 +262,11 @@ let wantAgentInfo = { ...@@ -261,10 +262,11 @@ let wantAgentInfo = {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
wantAgent = data; wantAgent = data;
}); if (wantAgent) {
WantAgent.getBundleName(wantAgent).then((data) => {
WantAgent.getBundleName(wantAgent).then((data) => { console.info('==========================>getBundleNameCallback=======================>');
console.info('==========================>getBundleNameCallback=======================>'); });
}
}); });
``` ```
...@@ -300,8 +302,15 @@ function getWantAgentCallback(err, data) { ...@@ -300,8 +302,15 @@ function getWantAgentCallback(err, data) {
if (err.code == 0) { if (err.code == 0) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('----getWantAgent failed!----'); console.error('getWantAgent failed, error: ' + JSON.stringify(err));
return;
} }
// getUid callback
function getUidCallback(err, data) {
console.info('==========================>getUidCallback=======================>');
}
WantAgent.getUid(wantAgent, getUidCallback);
} }
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -332,12 +341,6 @@ let wantAgentInfo = { ...@@ -332,12 +341,6 @@ let wantAgentInfo = {
} }
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
// getUid callback
function getUidCallback(err, data) {
console.info('==========================>getUidCallback=======================>');
}
WantAgent.getUid(wantAgent, getUidCallback);
``` ```
...@@ -402,10 +405,11 @@ let wantAgentInfo = { ...@@ -402,10 +405,11 @@ let wantAgentInfo = {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
wantAgent = data; wantAgent = data;
}); if (wantAgent) {
WantAgent.getUid(wantAgent).then((data) => {
WantAgent.getUid(wantAgent).then((data) => { console.info('==========================>getUidCallback=======================>');
console.info('==========================>getUidCallback=======================>'); });
}
}); });
``` ```
...@@ -440,8 +444,15 @@ function getWantAgentCallback(err, data) { ...@@ -440,8 +444,15 @@ function getWantAgentCallback(err, data) {
if (err.code == 0) { if (err.code == 0) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('----getWantAgent failed!----'); console.error('getWantAgent failed, error: ' + JSON.stringify(err));
return;
} }
// cancel callback
function cancelCallback(err, data) {
console.info('==========================>cancelCallback=======================>');
}
WantAgent.cancel(wantAgent, cancelCallback);
} }
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -472,12 +483,6 @@ let wantAgentInfo = { ...@@ -472,12 +483,6 @@ let wantAgentInfo = {
} }
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
// cancel callback
function cancelCallback(err, data) {
console.info('==========================>cancelCallback=======================>');
}
WantAgent.cancel(wantAgent, cancelCallback);
``` ```
...@@ -542,10 +547,11 @@ let wantAgentInfo = { ...@@ -542,10 +547,11 @@ let wantAgentInfo = {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
wantAgent = data; wantAgent = data;
}); if (wantAgent) {
WantAgent.cancel(wantAgent).then((data) => {
WantAgent.cancel(wantAgent).then((data) => { console.info('==========================>cancelCallback=======================>');
console.info('==========================>cancelCallback=======================>'); });
}
}); });
``` ```
...@@ -582,8 +588,19 @@ function getWantAgentCallback(err, data) { ...@@ -582,8 +588,19 @@ function getWantAgentCallback(err, data) {
if (err.code == 0) { if (err.code == 0) {
wantAgent = data; wantAgent = data;
} else { } else {
console.info('----getWantAgent failed!----'); console.error('getWantAgent failed, error: ' + JSON.stringify(err));
return;
}
// trigger callback
function triggerCallback(data) {
console.info('==========================>triggerCallback=======================>');
}
var triggerInfo = {
code:0
} }
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback)
} }
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -614,16 +631,6 @@ let wantAgentInfo = { ...@@ -614,16 +631,6 @@ let wantAgentInfo = {
} }
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
// trigger callback
function triggerCallback(data) {
console.info('==========================>triggerCallback=======================>');
}
var triggerInfo = {
code:0
}
WantAgent.trigger(wantAgent, triggerInfo, triggerCallback)
``` ```
...@@ -661,8 +668,15 @@ function getWantAgentCallback(err, data) { ...@@ -661,8 +668,15 @@ function getWantAgentCallback(err, data) {
wantAgent1 = data; wantAgent1 = data;
wantAgent2 = data; wantAgent2 = data;
} else { } else {
console.info('----getWantAgent failed!----'); console.error('getWantAgent failed, error: ' + JSON.stringify(err));
return;
} }
// equal callback
function equalCallback(err, data) {
console.info('==========================>equalCallback=======================>');
}
WantAgent.equal(wantAgent1, wantAgent2, equalCallback)
} }
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -693,12 +707,6 @@ let wantAgentInfo = { ...@@ -693,12 +707,6 @@ let wantAgentInfo = {
} }
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
// equal callback
function equalCallback(err, data) {
console.info('==========================>equalCallback=======================>');
}
WantAgent.equal(wantAgent1, wantAgent2, equalCallback)
``` ```
...@@ -766,6 +774,11 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { ...@@ -766,6 +774,11 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
wantAgent1 = data; wantAgent1 = data;
wantAgent2 = data; wantAgent2 = data;
if (data) {
WantAgent.equal(wantAgent1, wantAgent2).then((data) => {
console.info('==========================>equalCallback=======================>');
});
}
}); });
WantAgent.equal(wantAgent1, wantAgent2).then((data) => { WantAgent.equal(wantAgent1, wantAgent2).then((data) => {
...@@ -827,11 +840,12 @@ let wantAgentInfo = { ...@@ -827,11 +840,12 @@ let wantAgentInfo = {
WantAgent.getWantAgent(wantAgentInfo).then((data) => { WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>'); console.info('==========================>getWantAgentCallback=======================>');
wantAgent = data; wantAgent = data;
if (data) {
WantAgent.getOperationType(wantAgent, (OperationType) => {
console.log('----------- getOperationType ----------, OperationType: ' + OperationType);
})
}
}); });
WantAgent.getOperationType(wantAgent, (OperationType) => {
console.log('----------- getOperationType ----------, OperationType: ' + OperationType);
})
``` ```
## WantAgent.getOperationType<sup>9+</sup> ## WantAgent.getOperationType<sup>9+</sup>
...@@ -901,7 +915,6 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { ...@@ -901,7 +915,6 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => {
}); });
``` ```
## WantAgentFlags ## WantAgentFlags
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -940,5 +953,5 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { ...@@ -940,5 +953,5 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => {
| info | WantAgent | Yes | A triggered **WantAgent** object. | | info | WantAgent | Yes | A triggered **WantAgent** object. |
| want | Want | Yes | An existing triggered **want**. | | want | Want | Yes | An existing triggered **want**. |
| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| | finalCode | number | Yes | Request code that triggers the **WantAgent** object.|
| finalData | string | No | Final data collected by the common event. | | finalData | string | Yes | Final data collected by the common event. |
| extraInfo | {[key: string]: any} | No | Extra information. | | extraInfo | {[key: string]: any} | No | Extra information. |
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册