diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md index 37bf04c704a91f0580fddf99b14f9f52fb94d683..fe5b7cfde18961802383469c3d2558f8c8381f67 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export ## Modules to Import ```ts -import ability from '@ohos.ability.ability' +import ability from '@ohos.ability.ability'; ``` **System capability**: SystemCapability.Ability.AbilityBase diff --git a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index f1301ad877dcf5a0bd2fec5ad5be10452ee88716..0f098c2398a1a3559f3a25873a8fe2cc81c3a898 100644 --- a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI. **Example** ```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. ```ts let id = 1122; let uri = dataUriUtils.attachId( - "com.example.dataUriUtils", + 'com.example.dataUriUtils', id, -) +); ``` @@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI. **Example** ```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. ```ts let id = 1122; let uri = dataUriUtils.updateId( - "com.example.dataUriUtils/1221", + 'com.example.dataUriUtils/1221', id -) +); ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index dc0e8ae8928a9191f70b555e84a3f58b09e4b876..143a2344a935a013e664bde170ef615e0f6acfba 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab ## Modules to Import ```ts -import errorCode from '@ohos.ability.errorCode' +import errorCode from '@ohos.ability.errorCode'; ``` ## ErrorCode diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index 96a44539760ea5f0cd261b4dd24446ed2589e31f..d6c2e8b781a85827687590f9863063821b892599 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -27,7 +27,7 @@ Enumerates the ability states. This enum can be used together with [AbilityRunni | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | | FOREGROUNDING | 11 | The ability is in the 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 @@ -63,7 +63,7 @@ const config = { language: 'Zh-Hans', // Simplified Chinese. colorMode: COLOR_MODE_LIGHT, // Light theme. direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; @@ -121,7 +121,7 @@ const config = { language: 'Zh-Hans', // Simplified Chinese. colorMode: COLOR_MODE_LIGHT, // Light theme. direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; @@ -131,7 +131,7 @@ try { console.log('updateConfiguration success.'); }).catch((err) => { console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.log('error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); @@ -310,7 +310,7 @@ try { console.log('getExtensionRunningInfos success, data: ' + JSON.stringify(data)); }).catch((err) => { console.log('getExtensionRunningInfos fail, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.log('error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); @@ -384,5 +384,5 @@ abilityManager.getTopAbility().then((data) => { console.log('getTopAbility success, data: ' + JSON.stringify(data)); }).catch((err) => { console.log('getTopAbility fail, err: ' + JSON.stringify(err)); -}) +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index 95fb225ff057fec05b73df3622629c45f83e2d15..513962a1b6f9799566af958d07a32d5498c9f3bf 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -45,7 +45,7 @@ appManager.isRunningInStabilityTest((err, flag) => { } else { console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); } -}) +}); ``` @@ -151,7 +151,7 @@ appManager.isRamConstrainedDevice((err, data) => { } else { console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); } -}) +}); ``` ## appManager.getAppMemorySize @@ -221,7 +221,7 @@ appManager.getAppMemorySize((err, data) => { } else { console.log('The size of app memory is:' + JSON.stringify(data)); } -}) +}); ``` ## appManager.getProcessRunningInformation @@ -299,7 +299,7 @@ appManager.getProcessRunningInformation((err, data) => { } else { console.log('The process running information is:' + JSON.stringify(data)); } -}) +}); ``` ## appManager.on @@ -356,7 +356,7 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; try { const observerId = appManager.on('applicationState', applicationStateObserver); console.log(`[appManager] observerCode: ${observerId}`); @@ -420,7 +420,7 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); @@ -482,7 +482,7 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); @@ -563,7 +563,7 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); @@ -578,7 +578,7 @@ try { console.log('unregisterApplicationStateObserver success, data: ' + JSON.stringify(data)); }).catch((err) => { console.log('unregisterApplicationStateObserver faile, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.log('error: ' + paramError.code + ', ' + paramError.message); } @@ -664,7 +664,7 @@ appManager.getForegroundApplications().then((data) => { console.log('getForegroundApplications success, data: ' + JSON.stringify(data)); }).catch((err) => { console.log('getForegroundApplications fail, err: ' + JSON.stringify(err)); -}) +}); ``` ## appManager.killProcessWithAccount @@ -706,7 +706,7 @@ try { console.log('killProcessWithAccount success'); }).catch((err) => { console.error('killProcessWithAccount fail, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.error('error: ' + paramError.code + ', ' + paramError.message); } @@ -848,7 +848,7 @@ try { console.log('killProcessesByBundleName success.'); }).catch((err) => { console.log('killProcessesByBundleName fail, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.log('error: ' + paramError.code + ', ' + paramError.message); } @@ -944,7 +944,7 @@ try { console.log('clearUpApplicationData success.'); }).catch((err) => { console.log('clearUpApplicationData fail, err: ' + JSON.stringify(err)); - }) + }); } catch (paramError) { console.log('error: ' + paramError.code + ', ' + paramError.message); } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md index 5cc9b61b90fb3072aacf530fdaee0ae2633f7ac0..deb8b546e79c77d02785bed821691602098f2280 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -10,7 +10,7 @@ The **Common** module provides all level-2 module APIs for developers to export. ## Modules to Import ```ts -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; ``` **System capability**: SystemCapability.Ability.AbilityBase @@ -33,7 +33,7 @@ import common from '@ohos.app.ability.common' **Example** ```ts -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; let uiAbilityContext: common.UIAbilityContext; let abilityStageContext: common.AbilityStageContext; diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md index 88aab2d4026afac5edaf8c3c7ff58033976e3e66..8680cc4af5ec2f603ff15d6c6452a01d47d058f3 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -1,25 +1,19 @@ # @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** > > 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 - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | language | string | Yes| Yes| Language of the application, for example, **zh**.| -| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| 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:
- **COLOR_MODE_NOT_SET**: The color mode is not set.
- **COLOR_MODE_LIGHT**: light mode.
- **COLOR_MODE_DARK**: dark mode.| +| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation. The options are as follows:
- **DIRECTION_NOT_SET**: The screen orientation is not set.
- **DIRECTION_HORIZONTAL**: horizontal direction.
- **DIRECTION_VERTICAL**: vertical direction.| +| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Pixel density of the screen. The options are as follows:
- **SCREEN_DENSITY_NOT_SET**: The pixel density is not set.
- **SCREEN_DENSITY_SDPI**: 120.
- **SCREEN_DENSITY_MDPI**: 160.
- **SCREEN_DENSITY_LDPI**: 240.
- **SCREEN_DENSITY_XLDPI**: 320.
- **SCREEN_DENSITY_XXLDPI**: 480.
- **SCREEN_DENSITY_XXXLDPI**: 640.| | displayId | number | Yes| No| ID of the display where the application is located.| | hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| @@ -34,7 +28,7 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi onCreate(want, launchParam) { let envCallback = { onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; let direction = config.direction; @@ -45,10 +39,10 @@ For details about the fields, see the **ohos.app.ability.Configuration.d.ts** fi }; try { let applicationContext = this.context.getApplicationContext(); - let callbackId = applicationContext.on("environment", envCallback); - console.log("callbackId: " + callbackId); + let callbackId = applicationContext.on('environment', envCallback); + console.log('callbackId: ' + callbackId); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ' + paramError.code + ', ' + paramError.message); } } } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md index bd56e256603930f874c9ba2c064462c8fad594a8..7f7fd36c946eb19e33d5fb3649f105aafaae8d23 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md @@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | COLOR_MODE_LIGHT | 1 | Light mode.| -## ConfigurationConstant.Direction +## ConfigurationConstant.Direction9+ You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. @@ -38,7 +38,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | DIRECTION_HORIZONTAL | 1 | Horizontal direction.| -## ConfigurationConstant.ScreenDensity +## ConfigurationConstant.ScreenDensity9+ 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 | Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| +| SCREEN_DENSITY_NOT_SET | 0 | The screen pixel density is not set.| +| SCREEN_DENSITY_SDPI | 120 | The pixel density of the screen is 'sdpi'.| +| SCREEN_DENSITY_MDPI | 160 | The pixel density of the screen is 'mdpi'.| +| SCREEN_DENSITY_LDPI | 240 | The pixel density of the screen is 'ldpi'.| +| SCREEN_DENSITY_XLDPI | 320 | The pixel density of the screen is 'xldpi'.| +| SCREEN_DENSITY_XXLDPI | 480 | The pixel density of the screen is 'xxldpi'.| +| SCREEN_DENSITY_XXXLDPI | 640 | The pixel density of the screen is 'xxxldpi'.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index 0cb95a9abfd6b90f1efacc431070ef6b3397e1e6..3ce5c5aa9b6b01015c5ec4c1b6dc0fe2c9b61e51 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -11,7 +11,7 @@ The **EnvironmentCallback** module provides the **onConfigurationUpdated** API f ## Modules to Import ```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. | -------- | -------- | -------- | -------- | | 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** ```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() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); - let EnvironmentCallback = { + let environmentCallback = { 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. let applicationContext = globalThis.applicationContext; // 2. Register a listener for the environment changes through the applicationContext object. - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + callbackId = applicationContext.registerEnvironmentCallback(environmentCallback); + console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId)); } onDestroy() { let applicationContext = globalThis.applicationContext; applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error)); }); } } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md index e543a93e9ceb5af52f3cdb939a0cfd5d24145968..d70d4bff58a9480072be1a007a0c77624be8f3a6 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -1,19 +1,19 @@ # @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** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```ts +``` import errorManager from '@ohos.app.ability.errorManager' ``` ## ErrorManager.on -on(type: "error", observer: ErrorObserver): number; +on(type: 'error', observer: ErrorObserver): number; Registers an error observer. @@ -23,34 +23,27 @@ Registers an error observer. | 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.| -**Return value** - - | Type| Description| - | -------- | -------- | - | number | Index of the observer.| - **Example** -```ts -var observer = { +```js +let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) + console.log('onUnhandledException, errorMsg: ', errorMsg); } -} -var observerId = -1; +}; try { - observerId = errorManager.on("error", observer); + errorManager.on('error', observer); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` ## ErrorManager.off -off(type: "error", observerId: number, callback: AsyncCallback\): void; +off(type: 'error', observerId: number, callback: AsyncCallback\): void; 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 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| -| observerId | number | Yes| Index of the observer returned by **on()**.| +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Digital code of the observer.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```ts -var observerId = 100; +```js +let observerId = 100; function unregisterErrorObserverCallback(err) { if (err) { @@ -75,15 +68,15 @@ function unregisterErrorObserverCallback(err) { } } try { - errorManager.off("error", observerId, unregisterErrorObserverCallback); + errorManager.off('error', observerId, unregisterErrorObserverCallback); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` ## ErrorManager.off -off(type: "error", observerId: number): Promise\; +off(type: 'error', observerId: number): Promise\; 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| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| -| observerId | number | Yes| Index of the observer returned by **on()**.| +| type | string | Yes| Type of the API to call.| +| observerId | number | Yes| Digital code of the observer.| **Return value** @@ -104,18 +97,18 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** -```ts -var observerId = 100; +```js +let observerId = 100; try { - errorManager.off("error", observerId) + errorManager.off('error', observerId) .then((data) => { console.log('----------- unregisterErrorObserver success ----------', data); }) .catch((err) => { console.log('----------- unregisterErrorObserver fail ----------', err); - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 434fb19383e072a36352012300c2a755769d6c1f..4448d79d41f3721b0d218a749757494bb65deb2f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -18,7 +18,7 @@ ohos.permission.MANAGE_MISSIONS ## missionManager.on -on(type:"mission", listener: MissionListener): number; +on(type:'mission', listener: MissionListener): number; Registers a listener to observe the mission status. @@ -43,69 +43,26 @@ Registers a listener to observe the mission status. **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager'; -import UIAbility from '@ohos.app.ability.UIAbility'; - -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} -}; - -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; - } - } -}; + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} + }; + console.log('registerMissionListener'); + try { + let listenerid = missionManager.on('mission', listener); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } ``` ## missionManager.off -off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; +off(type: 'mission', listenerId: number, callback: AsyncCallback<void>): void; Deregisters a mission status listener. @@ -119,75 +76,36 @@ Deregisters a mission status listener. | 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<void> | Yes| Callback used to return the result.| **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager'; -import UIAbility from '@ohos.app.ability.UIAbility'; - -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} -}; - -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, (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; - } - } -}; + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} + }; + console.log('registerMissionListener'); + try { + let listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid, (error) => { + console.log('unregisterMissionListener'); + }); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } ``` ## missionManager.off -off(type: "mission", listenerId: number): Promise<void>; +off(type: 'mission', listenerId: number): Promise<void>; 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 | 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** @@ -212,63 +130,24 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager'; -import UIAbility from '@ohos.app.ability.UIAbility'; - -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} -}; - -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; - } - } -}; + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');} + }; + console.log('registerMissionListener'); + try { + let listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid).catch(function (err) { + console.log(err); + }); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } ``` @@ -297,28 +176,19 @@ Obtains the information about a given mission. This API uses an asynchronous cal ```ts import missionManager from '@ohos.app.ability.missionManager'; - let testMissionId = 1; try { - var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); - if (allMissions && allMissions.length > 0) { - testMissionId = allMissions[0].missionId; - } - - missionManager.getMissionInfo("", testMissionId, (error, mission) => { - if (error) { - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - } else { - console.log("mission.missionId = " + mission.missionId); - console.log("mission.runningState = " + mission.runningState); - console.log("mission.lockedState = " + mission.lockedState); - console.log("mission.timestamp = " + mission.timestamp); - console.log("mission.label = " + mission.label); - console.log("mission.iconPath = " + mission.iconPath); - } - }); + let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);}); + missionManager.getMissionInfo('', allMissions[0].missionId, (error, mission) => { + console.log('getMissionInfo is called, error.code = ' + error.code); + console.log('mission.missionId = ' + mission.missionId); + console.log('mission.runningState = ' + mission.runningState); + console.log('mission.lockedState = ' + mission.lockedState); + console.log('mission.timestamp = ' + mission.timestamp); + console.log('mission.label = ' + mission.label); + console.log('mission.iconPath = ' + mission.iconPath); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + 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 **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 1; -try { - missionManager.getMissionInfo("", testMissionId).then((data) => { - console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getMissionInfo failed. Cause: ' + error.message); + try { + let mission = missionManager.getMissionInfo('', 10).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('getMissionInfo failed. Cause: ' + error.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.getMissionInfos @@ -391,17 +259,13 @@ Obtains information about all missions. This API uses an asynchronous callback t import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - } else { - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - } - }) + 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)); + }); } 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 **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -try { - missionManager.getMissionInfos("", 10).then((data) => { - console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getMissionInfos failed. Cause: ' + error.message); + try { + let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('getMissionInfos failed. Cause: ' + error.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.getMissionSnapShot @@ -468,22 +331,27 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.getMissionSnapShot("", testMissionId, (err, data) => { - if (err) { - console.error('getMissionSnapShot failed:' + err.message); - } else { - console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); - } + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + 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) { - console.error('getMissionSnapShot failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.getMissionSnapShot @@ -511,20 +379,26 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.getMissionSnapShot("", testMissionId).then((data) => { - console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getMissionSnapShot failed. Cause: ' + error.message); - }); -} catch (error) { - console.error('getMissionSnapShot failed. Cause: ' + error.message); -} -``` + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + 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 @@ -547,22 +421,27 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => { - if (err) { - console.error('getLowResolutionMissionSnapShot failed:' + err.message); - } else { - console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); - } + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + 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) { - console.error('getLowResolutionMissionSnapShot failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.getLowResolutionMissionSnapShot @@ -591,20 +470,25 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { - console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); - }); -} catch (error) { - console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); -} -``` + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; + + let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` ## missionManager.lockMission @@ -628,22 +512,25 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.lockMission(testMissionId, (err, data) => { - if (err) { - console.error('lockMission failed:' + err.message); - } else { - console.info('lockMission successfully:' + JSON.stringify(data)); - } + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + let id = missions[0].missionId; + + missionManager.lockMission(id).then(() => { + console.log('lockMission is called '); + }); }); -} catch (err) { - console.error('lockMission failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.lockMission @@ -670,20 +557,27 @@ Locks a given mission. This API uses a promise to return the result. | Promise<void> | Promise used to return the result.| **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.lockMission(testMissionId).then((data) => { - console.info('lockMission successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('lockMission failed. Cause: ' + error.message); + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; + + missionManager.lockMission(id).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('lockMission failed. Cause: ' + error.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.unlockMission @@ -705,22 +599,26 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.unlockMission(testMissionId, (err, data) => { - if (err) { - console.error('unlockMission failed:' + err.message); - } else { - console.info('unlockMission successfully:' + JSON.stringify(data)); - } + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + let id = missions[0].missionId; + + missionManager.unlockMission(id).then(() => { + console.log('unlockMission is called '); + }); }); -} catch (err) { - console.error('unlockMission failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.unlockMission @@ -748,20 +646,29 @@ Unlocks a given mission. This API uses a promise to return the result. **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.unlockMission(testMissionId).then((data) => { - console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('unlockMission failed. Cause: ' + error.message); + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; + + missionManager.lockMission(id).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('unlockMission failed. Cause: ' + error.message); -} -``` + missionManager.unlockMission(id).catch(function (err){ + console.log(err); + }); + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.clearMission @@ -784,22 +691,24 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.clearMission(testMissionId, (err, data) => { - if (err) { - console.error('clearMission failed:' + err.message); - } else { - console.info('clearMission successfully:' + JSON.stringify(data)); - } + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + let id = missions[0].missionId; + + missionManager.clearMission(id).then(() => { + console.log('clearMission is called '); + }); }); -} catch (err) { - console.error('clearMission failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` ## missionManager.clearMission @@ -828,20 +737,26 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.clearMission(testMissionId).then((data) => { - console.info('clearMission successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('clearMission failed. Cause: ' + error.message); + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; + + missionManager.clearMission(id).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('clearMission failed. Cause: ' + error.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.clearAllMissions @@ -857,21 +772,14 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + missionManager.clearAllMissions().then(() => { + console.log('clearAllMissions is called '); + }); + ``` -try { - missionManager.clearAllMissions(err => { - if (err) { - console.error('clearAllMissions failed:' + err.message); - } else { - console.info('clearAllMissions successfully.'); - } - }); -} catch (err) { - console.error('clearAllMissions failed:' + err.message); -} -``` ## missionManager.clearAllMissions @@ -893,19 +801,13 @@ Clears all unlocked missions. This API uses a promise to return the result. **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + 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 @@ -928,22 +830,25 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.moveMissionToFront(testMissionId, (err, data) => { - if (err) { - console.error('moveMissionToFront failed:' + err.message); - } else { - console.info('moveMissionToFront successfully:' + JSON.stringify(data)); - } + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + let id = missions[0].missionId; + + missionManager.moveMissionToFront(id).then(() => { + console.log('moveMissionToFront is called '); + }); }); -} catch (err) { - console.error('moveMissionToFront failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.moveMissionToFront @@ -967,22 +872,25 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { - if (err) { - console.error('moveMissionToFront failed:' + err.message); - } else { - console.info('moveMissionToFront successfully:' + JSON.stringify(data)); - } + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + console.log('size = ' + missions.length); + console.log('missions = ' + JSON.stringify(missions)); + let id = missions[0].missionId; + + missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { + console.log('moveMissionToFront is called '); + }); }); -} catch (err) { - console.error('moveMissionToFront failed:' + err.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` + ## missionManager.moveMissionToFront @@ -1011,17 +919,22 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** -```ts -import missionManager from '@ohos.app.ability.missionManager'; + ```ts + import missionManager from '@ohos.app.ability.missionManager'; -let testMissionId = 2; -try { - missionManager.moveMissionToFront(testMissionId).then((data) => { - console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('moveMissionToFront failed. Cause: ' + error.message); + try { + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; + + missionManager.moveMissionToFront(id).catch(function (err){ + console.log(err); }); -} catch (error) { - console.error('moveMissionToFront failed. Cause: ' + error.message); -} -``` + } catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index a2090ed00e60cac1b5452bf6357f47cfb3c7be2e..defd004f2a492be2d93a039301af1caff3bf2012 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -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. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -24,7 +24,7 @@ Defines the quick fix information at the HAP file level. | ----------- | -------------------- | ---- | ------------------------------------------------------------ | | moduleName | string | Yes | Name 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 @@ -57,25 +57,31 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| +| callback | AsyncCallback\ | 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** - + ```ts + import quickFixManager from '@ohos.app.ability.quickFixManager'; + try { - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf']; quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { if (error) { - console.info( `applyQuickFix failed with error + ${error}`) + console.info( `applyQuickFix failed with error + ${error}`); } else { - console.info( 'applyQuickFix success') + console.info( 'applyQuickFix success'); } - }) + }); } 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. **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise\ | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| **Example** - + ```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 { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { - console.info('applyQuickFix success') + console.info('applyQuickFix success'); }).catch((error) => { - console.info(`applyQuickFix err: + ${error}`) - }) + console.info(`applyQuickFix err: + ${error}`); + }); } 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 | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| **Example** - + ```ts + import quickFixManager from '@ohos.app.ability.quickFixManager'; + try { - let bundleName = "bundleName" + let bundleName = 'bundleName'; quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { if (error) { - console.info(`getApplicationQuickFixInfo error: + ${error}`) + console.info(`getApplicationQuickFixInfo error: + ${error}`); } else { - console.info(`getApplicationQuickFixInfo success: + ${data}`) + console.info(`getApplicationQuickFixInfo success: + ${data}`); } - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } + console.log('error: ' + paramError.code + ', ' + paramError.message); + } ``` ## quickFixManager.getApplicationQuickFixInfo @@ -174,21 +184,23 @@ Obtains the quick fix information of the application. This API uses a promise to **Return value** - | Type| Description| - | -------- | -------- | - | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| +| Type| Description| +| -------- | -------- | +| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| **Example** ```ts + import quickFixManager from '@ohos.app.ability.quickFixManager'; + try { - let bundleName = "bundleName" + let bundleName = 'bundleName'; quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { - console.info(`getApplicationQuickFixInfo success: + ${data}`) + console.info(`getApplicationQuickFixInfo success: + ${data}`); }).catch((error) => { - console.info(`getApplicationQuickFixInfo err: + ${error}`) - }) + console.info(`getApplicationQuickFixInfo err: + ${error}`); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ' + paramError.code + ', ' + paramError.message); } - ``` +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 0efdb59d5eaed4c2b70e5ff666b0c9d63b11212f..effff8a5277344b18c274847808dae7897c85866 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -1,10 +1,10 @@ # @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** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -80,7 +80,7 @@ Called when this ServiceExtensionAbility is destroyed to clear resources. 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 @@ -129,7 +129,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal **Example** ```ts - import rpc from '@ohos.rpc' + import rpc from '@ohos.rpc'; class StubTest extends rpc.RemoteObject{ constructor(des) { super(des); @@ -140,7 +140,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal class ServiceExt extends ServiceExtension { onConnect(want) { 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 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 @@ -176,7 +176,7 @@ Called when a client is disconnected from this ServiceExtensionAbility. 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 @@ -246,7 +246,8 @@ Dumps the client information. class ServiceExt extends ServiceExtension { onDump(params) { console.log('dump, params:' + JSON.stringify(params)); - return ["params"] + return ['params']; } } ``` + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index 8f5dc4b7ac8e5d7559146e9fe450155962bebb70..15537809d895c239afa2a988ec5e9f806ac5007a 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -16,7 +16,7 @@ import StartOptions from '@ohos.app.ability.StartOptions'; ## Attributes -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 38d9f5428c37873ae9f786ed0f391142f30a011b..127add25d18fbeda45b6bd44bd82f3dd74a5540b 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -1,9 +1,10 @@ # @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). -- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). +This module provides the following common ability-related functions: +- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). +- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. > **NOTE** > @@ -13,7 +14,7 @@ UIAbility is an application component that has the UI. The **UIAbility** module ## Modules to Import ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; +import Ability from '@ohos.app.ability.UIAbility'; ``` ## Attributes @@ -22,16 +23,16 @@ import UIAbility from '@ohos.app.ability.UIAbility'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| -| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| -| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.| +| 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 ability.| +| 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.| -## UIAbility.onCreate +## Ability.onCreate 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 @@ -39,13 +40,13 @@ Called to initialize the service logic when a UIAbility is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.| -| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| +| 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 ability, and the reason for the last abnormal exit.| **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -53,11 +54,11 @@ Called to initialize the service logic when a UIAbility is created. ``` -## UIAbility.onWindowStageCreate +## Ability.onWindowStageCreate 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 @@ -70,7 +71,7 @@ Called when a **WindowStage** is created for this UIAbility. **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); } @@ -78,18 +79,18 @@ Called when a **WindowStage** is created for this UIAbility. ``` -## UIAbility.onWindowStageDestroy +## Ability.onWindowStageDestroy 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 **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onWindowStageDestroy() { console.log('onWindowStageDestroy'); } @@ -97,11 +98,11 @@ Called when the **WindowStage** is destroyed for this UIAbility. ``` -## UIAbility.onWindowStageRestore +## Ability.onWindowStageRestore 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 @@ -114,7 +115,7 @@ Called when the **WindowStage** is restored during the migration of this UIAbili **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); } @@ -122,18 +123,18 @@ Called when the **WindowStage** is restored during the migration of this UIAbili ``` -## UIAbility.onDestroy +## Ability.onDestroy 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 **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onDestroy() { console.log('onDestroy'); } @@ -141,18 +142,18 @@ Called when this UIAbility is destroyed to clear resources. ``` -## UIAbility.onForeground +## Ability.onForeground 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 **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onForeground() { console.log('onForeground'); } @@ -160,18 +161,18 @@ Called when this UIAbility is switched from the background to the foreground. ``` -## UIAbility.onBackground +## Ability.onBackground 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 **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onBackground() { console.log('onBackground'); } @@ -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; @@ -202,22 +203,22 @@ Called to save data during the ability migration preparation process. **Example** ```ts - import AbilityConstant from "@ohos.app.ability.AbilityConstant" + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); - wantParams["myData"] = "my1234567"; + wantParams['myData'] = 'my1234567'; return AbilityConstant.OnContinueResult.AGREE; } } ``` -## UIAbility.onNewWant +## Ability.onNewWant 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 @@ -226,20 +227,20 @@ Called when a new Want is passed in and this UIAbility is started again. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| -| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| +| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the ability startup and the last abnormal exit.| **Example** ```ts - class MyUIAbility extends UIAbility { + class MyUIAbility extends UIAbility { onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); - } - } + } + } ``` -## UIAbility.onDump +## Ability.onDump onDump(params: Array\): Array\; @@ -256,20 +257,20 @@ Dumps client information. **Example** ```ts - class MyUIAbility extends UIAbility { + class myAbility extends Ability { onDump(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; -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 @@ -277,24 +278,24 @@ Called when the framework automatically saves the UIAbility state in the case of | 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: string]: any} | Yes| **want** parameter.| **Return value** | 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** ```ts -import AbilityConstant from '@ohos.app.ability.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); - wantParam["myData"] = "my1234567"; + wantParam['myData'] = 'my1234567'; return AbilityConstant.OnSaveResult.RECOVERY_AGREE; } } @@ -338,9 +339,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - class MyMessageAble{ // Custom sequenceable data structure. - name:"" - str:"" + import Ability from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ // ×Ô¶¨ÒåµÄSequenceableÊý¾Ý½á¹¹ + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -359,17 +361,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error return true; } }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities. - var caller; - export default class MainUIAbility extends UIAbility { + let method = 'call_Function'; // Notification message string negotiated by the two abilities. + let caller; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainAbility', + deviceId: '' }).then((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) .then(() => { console.log('Caller call() called'); @@ -419,9 +422,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ - name:"" - str:"" + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -440,21 +444,21 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error return true; } }; - var method = 'call_Function'; - var caller; - export default class MainUIAbility extends UIAbility { + let method = 'call_Function'; + let caller; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainAbility', + deviceId: '' }).then((obj) => { caller = obj; - let msg = new MyMessageAble(1, "world"); + let msg = new MyMessageAble(1, 'world'); caller.callWithResult(method, msg) .then((data) => { console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); + let retmsg = new MyMessageAble(0, ''); data.readSequenceable(retmsg); }) .catch((callErr) => { @@ -490,13 +494,14 @@ Releases the caller interface of the target ability. **Example** ```ts - var caller; - export default class MainUIAbility extends UIAbility { + import Ability from '@ohos.app.ability.UIAbility'; + let caller; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainAbility', + deviceId: '' }).then((obj) => { caller = obj; try { @@ -525,18 +530,19 @@ Registers a callback that is invoked when the stub on the target ability is disc | 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** ```ts - var caller; - export default class MainUIAbility extends UIAbility { + import Ability from '@ohos.application.Ability'; + let caller; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainAbility', + deviceId: '' }).then((obj) => { caller = obj; try { @@ -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); }); } 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)); } }).catch((err) => { @@ -557,7 +563,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ## 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. @@ -568,7 +574,7 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **release**.| -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| **Error codes** @@ -581,17 +587,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - var caller; - export default class MainUIAbility extends UIAbility { + import Ability from '@ohos.app.ability.UIAbility'; + let caller; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainAbility', + deviceId: '' }).then((obj) => { caller = obj; try { - caller.on("release", (str) => { + caller.on('release', (str) => { console.log(' Caller OnRelease CallBack is called ' + str); }); } catch (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 @@ -624,7 +733,7 @@ Registers a caller notification callback, which is invoked when the target abili | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | method | string | Yes| Notification message string negotiated between the two abilities.| -| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| +| 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** @@ -637,9 +746,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ - name:"" - str:"" + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -658,14 +768,14 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error return true; } }; - var method = 'call_Function'; + let method = 'call_Function'; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble("test", ""); + let msg = new MyMessageAble('test', ''); 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) { console.log('Callee onCreate is called'); try { @@ -704,8 +814,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - var method = 'call_Function'; - export default class MainUIAbility extends UIAbility { + import Ability from '@ohos.app.ability.UIAbility'; + let method = 'call_Function'; + export default class MainAbility extends Ability { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -736,4 +847,4 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 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.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index c96e29d90f3a10a563df41bc8a545cb42dfdeba4..947e07b6ca58321597ce6090ae0d41b9a1ca69ba 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -18,119 +18,118 @@ import Want from '@ohos.app.ability.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | -| bundleName | string | No | Bundle name of the ability.| -| moduleName | string | No| Name of the module to which the ability belongs.| +| deviceId | string | No | ID of the device running the ability. | +| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. | | 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). | -| [entities](js-apis-app-ability-wantConstant.md#wantconstantentity) | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| -| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | string | No| MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| +| 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.| +| 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, a number is passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags). | +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| entities | Array\ | 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** -- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). +- Basic usage ```ts let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "FuncAbility", - "moduleName": "entry" // moduleName is optional. + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.extreme.test', + 'abilityName': 'MainAbility', + 'moduleName': 'entry' // moduleName is optional }; this.context.startAbility(want, (error) => { // 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 ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { - keyForString: "str", + keyForString: 'str', }, - } + }; ``` * Number ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForInt: 100, keyForDouble: 99.99, }, - } + }; ``` * Boolean ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForBool: true, }, - } + }; ``` * Object ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForObject: { - keyForObjectString: "str", + keyForObjectString: 'str', keyForObjectInt: -200, keyForObjectDouble: 35.5, keyForObjectBool: false, }, }, - } + }; ``` * Array ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { - keyForArrayString: ["str1", "str2", "str3"], + keyForArrayString: ['str1', 'str2', 'str3'], keyForArrayInt: [100, 200, 300, 400], keyForArrayDouble: [0.1, 0.2], - keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + keyForArrayObject: [{obj1: 'aaa'}, {obj2: 100}], }, - } + }; ``` * File descriptor (FD) ```ts - import fileio from '@ohos.fileio'; - let fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(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} + import fileio from '@ohos.fileio'; + let fd; + try { + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); + } catch(e) { + console.log('openSync fail:' + JSON.stringify(e)); } - }; - this.context.startAbility(want, (error) => { + let want = { + '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. - console.log("error.code = " + error.code) - }) + console.log('error.code = ' + error.code); + }); ``` -- For more details and examples, see [Want](../../application-models/want-overview.md). - + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index 43b95743b25c34bdae9457c1e1ed1cf01f8e986e..e18ec1bd683485806f1ad79ec89a67db627125a6 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -1,6 +1,6 @@ # @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** > @@ -8,7 +8,7 @@ The **app.ability.WantAgent** module provides APIs for creating and comparing ** ## Modules to Import -```ts +```js import WantAgent from '@ohos.app.ability.wantAgent'; ``` @@ -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. | | callback | AsyncCallback\ | 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** -```ts -// WantAgent object -let wantAgent; +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -85,20 +62,12 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` @@ -124,43 +93,19 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -180,16 +125,14 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; try { WantAgent.getWantAgent(wantAgentInfo).then((data) => { - wantAgent = data; -}).catch((err) => { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); -}); -} catch (err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('==========================>getWantAgentCallback=======================>'); + }); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` @@ -210,45 +153,31 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | agent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + +//getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -268,33 +197,18 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 function getBundleNameCallback(err, data) { - if(err) { - 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)); + console.info('==========================>getBundleNameCallback=======================>'); } -} -try { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getBundleName(wantAgent, getBundleNameCallback); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` @@ -320,45 +234,22 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts - // WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; -// WantAgentInfo object + +//WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -378,29 +269,19 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + 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 | agent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\ | 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** -```ts +```js import WantAgent from '@ohos.app.ability.wantAgent'; -// WantAgent object + + +// wantAgent object let wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -480,33 +346,18 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 function getUidCallback(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.getUid(wantAgent, getUidCallback); - } catch(err) { - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('==========================>getUidCallback=======================>'); } -} -try { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getUid(wantAgent, getUidCallback); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` @@ -532,45 +383,22 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -590,33 +418,24 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + wantAgent = data; + }); + + WantAgent.getUid(wantAgent).then((data) => { + console.info('==========================>getUidCallback=======================>'); + }); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` + ## WantAgent.getWant getWant(agent: WantAgent, callback: AsyncCallback\): void @@ -634,45 +453,31 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba | agent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.| -**Error codes** -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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -692,33 +497,18 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { 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 | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -804,29 +571,19 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + 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 | agent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -905,33 +648,18 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { 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. | --------------- | ------------------------------- | | Promise\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1015,32 +720,24 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + wantAgent = data; + }); + + WantAgent.cancel(wantAgent).then((data) => { + console.info('==========================>cancelCallback=======================>'); + }); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` + + ## WantAgent.trigger trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void @@ -1054,52 +751,33 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ----------- | ----------------------------- | ---- | ------------------------------- | | 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.| -**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; -// triggerInfo -let triggerInfo = { - code: 0 // Custom result code. + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info('==========================>getWantAgentCallback=======================>'); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); } +} // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1119,33 +797,23 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { 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 | otherAgent | WantAgent | Yes | The second **WantAgent** object. | | callback | AsyncCallback\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent1; 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 let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1226,34 +881,18 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { 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 | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + + +// wantAgent object let wantAgent1; let wantAgent2; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1339,30 +955,20 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; -// getWantAgent callback -function getWantAgentCallback(err, data) { - if (err === undefined) { +try { + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; - } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); - } - try { - WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ - console.info('equal ok!' + JSON.stringify(data)); - }).catch((err)=>{ - 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)); + }); + + WantAgent.equal(wantAgent1, wantAgent2).then((data) => { + console.info('==========================>equalCallback=======================>'); + }); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); } ``` @@ -1381,45 +987,21 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron | agent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + +// wantAgent object let wantAgent; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1439,33 +1021,19 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + 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 | ----------------------------------------------------------- | ------------------------------------------------------------ | | Promise\ | 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** -```ts -// WantAgent object +```js +import WantAgent from '@ohos.app.ability.wantAgent'; + +// wantAgent object let wantAgent; + // WantAgentInfo object let wantAgentInfo = { wants: [ { deviceId: 'deviceId', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', action: 'action1', entities: ['entity1'], type: 'MIMETYPE', @@ -1547,29 +1091,21 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, 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 { - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info('==========================>getWantAgentCallback=======================>'); + 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 { | info | WantAgent | Yes | A triggered **WantAgent** object. | | want | Want | Yes | An existing triggered **want**. | | 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. | + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index 4d7a483eab8a55c91d4dbb89287fa611f980ef34..587ccf7a14e3ea5d393dde9feeeb0ecfbc80f163 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -8,7 +8,7 @@ The **wantConstant** module provides the actions, entities, and flags used in ** ## Modules to Import -```js +```ts import wantConstant from '@ohos.app.ability.wantConstant'; ``` @@ -79,4 +79,17 @@ 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_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_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to **[ohos.app.Context](js-apis-ability-context.md)**. | +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 51637975d72ea807f428f235aec90310f69b197f..39cfb8e3349b07ee745c1756cefb4ea66f189b39 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -35,7 +35,7 @@ Creates a **FormBindingData** object. | 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** @@ -48,17 +48,20 @@ Creates a **FormBindingData** object. **Example** ```ts -import fs from '@ohos.file.fs'; -import formBindingData from '@ohos.app.form.formBindingData'; - -try { - let fd = fs.openSync('/path/to/form.png') +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; +let context=featureAbility.getContext(); +context.getOrCreateLocalDir((err,data)=>{ + let path=data+'/xxx.jpg'; + let fd = fileio.openSync(path); let obj = { - "temperature": "21°", - "formImages": { "image": fd } + 'temperature': '21°', + 'formImages': {'image': fd} }; - formBindingData.createFormBindingData(obj); -} catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); -} + try { + formBindingData.createFormBindingData(obj); + } catch (error) { + console.log(`catch err->${JSON.stringify(err)}`); + } +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index e78cf3647a1298ed77b4993d811393ede4e2e5b6..c8c8ca6389aa86a7f2a065c98e125c5b1faaca29 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -1,6 +1,6 @@ -# @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** > @@ -34,26 +34,25 @@ Deletes a widget. After this API is called, the application can no longer use th | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; - formHost.deleteForm(formId, (error) => { + var formId = '12400633174999288'; + formHost.deleteForm(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost deleteForm, error:' + JSON.stringify(error)); } else { console.log('formHost deleteForm success'); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.log(`catch err->${JSON.stringify(error)}`); } + ``` ## deleteForm @@ -83,23 +82,21 @@ Deletes a widget. After this API is called, the application can no longer use th | 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).| **Parameters** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; + var formId = '12400633174999288'; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost deleteForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; - formHost.releaseForm(formId, (error) => { + var formId = '12400633174999288'; + formHost.releaseForm(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost releaseForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error) => { + var formId = '12400633174999288'; + formHost.releaseForm(formId, true, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost releaseForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; + var formId = '12400633174999288'; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost releaseForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; - formHost.requestForm(formId, (error) => { + var formId = '12400633174999288'; + formHost.requestForm(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost requestForm, error:' + JSON.stringify(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. | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; + var formId = '12400633174999288'; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost requestForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; - formHost.castToNormalForm(formId, (error) => { + var formId = '12400633174999288'; + formHost.castToNormalForm(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost castTempForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = "12400633174999288"; + var formId = '12400633174999288'; formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost castTempForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error) => { + var formId = ['12400633174999288']; + formHost.notifyVisibleForms(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; + var formId = ['12400633174999288']; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyVisibleForms, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error) => { + var formId = ['12400633174999288']; + formHost.notifyInvisibleForms(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; + var formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error) => { + var formId = ['12400633174999288']; + formHost.enableFormsUpdate(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; + var formId = ['12400633174999288']; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost enableFormsUpdate, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error) => { + var formId = ['12400633174999288']; + formHost.disableFormsUpdate(formId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formId = ["12400633174999288"]; + var formId = ['12400633174999288']; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost disableFormsUpdate, error:' + JSON.stringify(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 **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { + var formId = '12400633174999288'; formHost.isSystemReady((error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost isSystemReady, error:' + JSON.stringify(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 **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { + var formId = '12400633174999288'; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost isSystemReady, error:' + JSON.stringify(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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 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<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { formHost.getAllFormsInfo((error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } }); } 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 | Type | Description | | :----------------------------------------------------------- | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } 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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } 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 | Type | Description | | :----------------------------------------------------------- | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - 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)); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost getFormsInfo, error:' + JSON.stringify(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 **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formIds = new Array("12400633174999288", "12400633174999289"); + var formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } }); } 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 **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - try { - let formIds = new Array("12400633174999288", "12400633174999289"); + var formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(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 | 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.| -| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | 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<[FormInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 +var want = { + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; try { formHost.acquireFormState(want, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } }); } 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. | Type | Description | | :------------ | :---------------------------------- | -| Promise<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| +| Promise<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| **Error codes** | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 +var want = { + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; try { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost acquireFormState, error:' + JSON.stringify(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<string>): void +on(type: 'formUninstall', callback: Callback<string>): void 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 | 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<string> | Yes| Callback used to return the widget ID.| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - let callback = function(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<string>): void +off(type: 'formUninstall', callback?: Callback<string>): void 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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | 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.
The value must be the same as that in **on("formUninstall")**.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| +| callback | Callback<string> | 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.
The value must be the same as that in **on('formUninstall')**.| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } -formHost.off("formUninstall", callback); +formHost.off('formUninstall', callback); ``` ## notifyFormsVisible @@ -1269,23 +1212,21 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +var formIds = new Array('12400633174999288', '12400633174999289'); try { - formHost.notifyFormsVisible(formIds, true, (error) => { + formHost.notifyFormsVisible(formIds, true, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +var formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyFormsVisible, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +var formIds = new Array('12400633174999288', '12400633174999289'); try { - formHost.notifyFormsEnableUpdate(formIds, true, (error) => { + formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +var formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.log(`catch err->${JSON.stringify(error)}`); } ``` ## shareForm @@ -1446,24 +1381,23 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca | 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).| + **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +var formId = '12400633174999288'; +var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; try { - formHost.shareForm(formId, deviceId, (error) => { + formHost.shareForm(formId, deviceId, (error, data) => { if (error) { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost shareForm, error:' + JSON.stringify(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 | 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).| **Example** ```ts -import formHost from '@ohos.app.form.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +var formId = '12400633174999288'; +var deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost shareForm, error:' + JSON.stringify(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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formIds | Array\ | Yes | ID of the widgets.| -| isProtected | boolean | Yes | Whether privacy protection is enabled.| -| callback | AsyncCallback\ | 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\, isProtected: boolean): Promise\; - -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\ | Yes | ID of the widgets.| -| isProtected | boolean | Yes | Whether privacy protection is enabled. | - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | 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).| | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID. | ```ts -import formHost from '@ohos.app.form.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +var formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost notifyFormsPrivacyProtected success'); + console.log('formHost shareForm success'); }).catch((error) => { - console.log(`error, code: ${error.code}, message: ${error.message}`); + console.log('formHost shareForm, error:' + JSON.stringify(error)); }); } catch(error) { - console.log(`catch error, code: ${error.code}, message: ${error.message}`); + console.log(`catch err->${JSON.stringify(error)}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index d61484f86b36bafd74ded1860272ac1a4b86089a..51b4fa42a1704ed9cf451daff6e2416a491db4a9 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -1,4 +1,4 @@ -# @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. @@ -31,25 +31,23 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback | 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).| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - -let formId = "12400633174999288"; +var formId = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); } else { console.log(`formProvider setFormNextRefreshTime success`); } }); } 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 | 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).| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - -let formId = "12400633174999288"; +var formId = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log(`formProvider setFormNextRefreshTime success`); + console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(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. | 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).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -import formProvider from '@ohos.app.form.formProvider'; - -let formId = "12400633174999288"; +var formId = '12400633174999288'; 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) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider updateForm, error:' + JSON.stringify(error)); } else { console.log(`formProvider updateForm success`); } }); } 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. | 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).| **Example** ```ts 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" }); +var formId = '12400633174999288'; +let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); try { formProvider.updateForm(formId, obj).then(() => { - console.log(`formProvider updateForm success`); + console.log('formProvider updateForm success'); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider updateForm, error:' + JSON.stringify(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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | 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).| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - try { formProvider.getFormsInfo((error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); } else { - console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.log(`catch err->${JSON.stringify(error)}`); } ``` ## getFormsInfo @@ -241,35 +231,33 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | 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).| **Example** ```ts -import formInfo from '@ohos.app.form.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter: formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName: "entry" +import formInfo from '@ohos.application.formInfo'; +const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName : 'entry' }; try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); } else { - console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); } }); -} catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} catch(error) { + 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 | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | 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).| **Example** ```ts -import formInfo from '@ohos.app.form.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter: formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName: "entry" +import formInfo from '@ohos.application.formInfo'; +const filter : formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName : 'entry' }; try { formProvider.getFormsInfo(filter).then((data) => { console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(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 | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| **Error codes** | 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).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -import formProvider from '@ohos.app.form.formProvider'; - -let want = { - abilityName: "FormAbility", +var want = { + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "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.module_name': 'entry' } }; try { - let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); + let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } 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 | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | | callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| **Error codes** | 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).| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - -let want = { - abilityName: "FormAbility", +var want = { + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "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.module_name': 'entry' } }; try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.log(`catch err->${JSON.stringify(error)}`); } + ``` ## requestPublishForm @@ -438,8 +421,8 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | **Return value** @@ -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| | -------- | -------- | -| 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).| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - -let want = { - abilityName: "FormAbility", +var want = { + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "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.module_name': 'entry' } }; try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(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 **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - try { formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error) { - console.log(`callback error, code: ${error.code}, message: ${error.message})`); - } else { - if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + if (error) { + console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + } else { + if (isSupported) { + var want = { + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + '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 { - formProvider.requestPublishForm(want, (error, data) => { - 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) { + console.log(`catch err->${JSON.stringify(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 **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - try { formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + } }; try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.log(`catch err->${JSON.stringify(error)}`); } + } }).catch((error) => { - console.log(`promise error, code: ${error.code}, message: ${error.message})`); + console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); }); } catch (error) { - console.log(`catch error, code: ${error.code}, message: ${error.message})`); + console.log(`catch err->${JSON.stringify(error)}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index ae72afeca2e3214d00a785c0639793e8df47d715..d022dd0177356fbbcd1d81031f1b505d009136c6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,10 +1,10 @@ # @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** > -> 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 @@ -43,7 +43,7 @@ Obtains the **AbilityDelegator** object of the application. **Example** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` @@ -65,8 +65,8 @@ Obtains the **AbilityDelegatorArgs** object of the application. **Example** ```ts -var args = AbilityDelegatorRegistry.getArguments(); -console.info("getArguments bundleName:" + args.bundleName); -console.info("getArguments testCaseNames:" + args.testCaseNames); -console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +let args = AbilityDelegatorRegistry.getArguments(); +console.info('getArguments bundleName:' + args.bundleName); +console.info('getArguments testCaseNames:' + args.testCaseNames); +console.info('getArguments testRunnerClassName:' + args.testRunnerClassName); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index e509a1b5d13a2d0d20b8d6dee4efee9487c5ee92..677884b754c5896b1a6af853d8a4df54355bbb85 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -4,13 +4,13 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying > **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. ## Modules to Import ```ts -import abilityManager from '@ohos.application.abilityManager' +import AbilityManager from '@ohos.application.abilityManager'; ``` ## AbilityState @@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the **Permission required**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Ability.AbilityRuntime.Core - + **Parameters** | Name | Type | Mandatory | Description | @@ -49,11 +49,13 @@ Updates the configuration. This API uses an asynchronous callback to return the **Example** ```ts -var config = { +import abilitymanager from '@ohos.application.abilityManager'; + +let config = { language: 'chinese' -} +}; -abilityManager.updateConfiguration(config, () => { +abilitymanager.updateConfiguration(config, () => { console.log('------------ updateConfiguration -----------'); }) ``` @@ -83,11 +85,13 @@ Updates the configuration. This API uses a promise to return the result. **Example** ```ts -var config = { +import abilitymanager from '@ohos.application.abilityManager'; + +let config = { language: 'chinese' -} +}; -abilityManager.updateConfiguration(config).then(() => { +abilitymanager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { console.log('updateConfiguration fail'); @@ -113,7 +117,9 @@ Obtains the ability running information. This API uses an asynchronous callback **Example** ```ts -abilityManager.getAbilityRunningInfos((err,data) => { +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos((err,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 **Example** ```ts -abilityManager.getAbilityRunningInfos().then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) -}).catch((err) => { - console.log("getAbilityRunningInfos err: " + err) -}); -``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): 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\> | 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)); -}); -``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number): Promise\> - -Obtains the extension running information. This API uses a promise to return the result. +import abilitymanager from '@ohos.application.abilityManager'; -**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.| - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| - -**Example** - -```ts -var upperLimit = 0; - -abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); +abilitymanager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); }).catch((err) => { console.log("getAbilityRunningInfos err: " + err); -}) -``` - -## getTopAbility9+ - -getTopAbility(callback: AsyncCallback\): 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)); }); ``` - -## getTopAbility9+ - -getTopAbility(): Promise\; - -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); -}) -``` diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index 501987d2db999b11f1997b2bfa8127860371c01d..7e36e015d708d150492f723ee059ff6664cb55e1 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API ## Modules to Import ```ts -import app from '@ohos.application.appManager'; +import appManager from '@ohos.application.appManager'; ``` ## appManager.isRunningInStabilityTest8+ @@ -161,7 +161,7 @@ getProcessRunningInfos(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. -> This API is deprecated since API Version 9. You are advised to use [appManager.getProcessRunningInformation9+](js-apis-app-ability-appManager.md#appmanagergetprocessrunninginformation9) instead. +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](js-apis-app-ability-appManager.md#appmanagergetprocessrunninginformation9) instead. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -189,7 +189,7 @@ getProcessRunningInfos(callback: AsyncCallback\>): vo Obtains information about the running processes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API Version 9. You are advised to use [appManager.getProcessRunningInformation9+](js-apis-app-ability-appManager.md#appmanagergetprocessrunninginformation9-1) instead. +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](js-apis-app-ability-appManager.md#appmanagergetprocessrunninginformation9-1) instead. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -199,7 +199,7 @@ Obtains information about the running processes. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| +| callback | AsyncCallback\> | Yes| Callback used to return the running processes. | **Example** @@ -359,7 +359,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | Yes| Numeric code of the observer.| @@ -421,7 +421,7 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). - + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 81870036a845c61f852f671616f63c12f92851b8..26220bafba6adf721e185f66752915f9370ab435 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,38 +1,27 @@ # @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** > 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. -## Modules to Import - -```ts -import Configuration from '@ohos.application.Configuration' -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language8+ | string | Yes| Yes| Language of the application, for example, **zh**.| +| language8+ | string | Yes| Yes| Language of the application.| | colorMode8+ | [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**.| -| direction9+ | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | [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).| -| displayId9+ | number | Yes| No| ID of the display where the application is located.| -| hasPointerDevice9+ | 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. **Example** ```ts -import hilog from '@ohos.hilog'; -import UIAbility from '@ohos.app.ability.UIAbility'; +import Ability from '@ohos.application.Ability'; import Window from '@ohos.window'; -export default class EntryAbility extends UIAbility { +export default class MainAbility extends Ability { onCreate(want, launchParam) { } @@ -42,13 +31,9 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: Window.WindowStage) { let envCallback = { onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; } }; @@ -57,12 +42,10 @@ export default class EntryAbility extends UIAbility { windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR); - hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + console.error('failed to load the content, error: + ${JSON.stringify(err)}'); return; } - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); - hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); + console.info('Succeeded in loading the content, data: + ${JSON.stringify(data)}'); }); } } diff --git a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md index dabe32b2f9d166dbce68b94c204b82f78b0090de..b1017a036bdb9f02a656c1890310cd3e029337f5 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -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_DARK | 0 | Dark mode.| | COLOR_MODE_LIGHT | 1 | Light mode.| - - -## ConfigurationConstant.Direction9+ - -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.ScreenDensity9+ - -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.| diff --git a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md index d4c25269235da3b95e4f230c084d92c1df047269..b6fdcadbee8d1518fb830f46db13270c82a77d11 100644 --- a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -1,17 +1,17 @@ # @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** > -> 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. ## Modules to Import ```ts -import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; +import EnvironmentCallback from '@ohos.application.EnvironmentCallback'; ``` @@ -30,48 +30,32 @@ Called when the system environment changes. | config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| ## EnvironmentCallback.onMemoryLevel - -onMemoryLevel(level: number): void; - -Called when the system memory level changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| - -**Example** + ```ts -import 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() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { 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. let applicationContext = globalThis.applicationContext; // 2. Register a listener for the environment changes through the applicationContext object. callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId)); } onDestroy() { let applicationContext = globalThis.applicationContext; applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error)); }); } } diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md index 5fbc52c95dc9e573947fb9820f00100a76a06f22..57e978adfb5fe88a505d99aa9175905cf3c1d1c4 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -35,7 +35,7 @@ Creates a **FormBindingData** object. | 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** @@ -48,17 +48,16 @@ Creates a **FormBindingData** object. **Example** ```ts -import formBindingData from @ohos.application.formBindingData; -import fs from '@ohos.file.fs'; - -try { - let fd = fs.openSync('/path/to/form.png') +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; +let context=featureAbility.getContext(); +context.getOrCreateLocalDir((err,data)=>{ + let path=data+'/xxx.jpg'; + let fd = fileio.openSync(path); let obj = { - "temperature": "21°", - "formImages": { "image": fd } + 'temperature': '21°', + 'formImages': {'image': fd} }; - formBindingData.createFormBindingData(obj); -} catch (error.code) { - console.log('catch error, error:' + JSON.stringify(error)); -} + let formBindingDataObj = formBindingData.createFormBindingData(obj); +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formHost.md b/en/application-dev/reference/apis/js-apis-application-formHost.md index 11da810effa714b8aaf37e35d3c0566556281ebf..67891daa343ff73efce912c073b9fe946947c739 100644 --- a/en/application-dev/reference/apis/js-apis-application-formHost.md +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -1,6 +1,6 @@ -# @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** > @@ -34,12 +34,10 @@ Deletes a widget. After this API is called, the application can no longer use th **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.deleteForm(formId, (error, data) => { 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 | -------- | -------- | | Promise<void> | Promise that returns no value.| -**Parameters** +**Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, (error, data) => { if (error.code) { - console.error('formHost releaseForm, error:' + JSON.stringify(error)); - } else { - console.log('formHost releaseForm success'); + console.log('formHost releaseForm, error:' + JSON.stringify(error)); } }); ``` @@ -132,14 +124,10 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, true, (error, data) => { if (error.code) { - console.error('formHost releaseForm, error:' + JSON.stringify(error)); - } else { - console.log('formHost releaseForm success'); + console.log('formHost releaseForm, error:' + JSON.stringify(error)); } }); ``` @@ -170,13 +158,11 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.requestForm(formId, (error, data) => { 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. **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.castTempForm(formId, (error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.castTempForm(formId).then(() => { console.log('formHost castTempForm success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId, (error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId, (error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId, (error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId, (error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.isSystemReady((error, data) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | 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<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - formHost.getAllFormsInfo((error, data) => { if (error.code) { - console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } @@ -668,17 +624,15 @@ Obtains the widget information provided by all applications on the device. This | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts - import formHost from '@ohos.application.formHost'; - formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); }).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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | bundleName | string | Yes| Bundle name of the application.| -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | 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<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - -formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { +formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => { if (error.code) { - console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { 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 | ------ | ------ | ---- | ------- | | bundleName | string | Yes| Bundle name of the application.| | moduleName | string | Yes| Module name.| -| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | 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<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - -formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { +formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => { if (error.code) { - console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); } 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 | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```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)); }).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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error, data) => { if (error.code) { - console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); } else { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.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 | 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.| -| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | 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<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; formHost.acquireFormState(want, (error, data) => { if (error.code) { - console.error('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log('formHost acquireFormState, error:' + JSON.stringify(error)); } else { 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. **Example** ```ts -import formHost from '@ohos.application.formHost'; - let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).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<string>): void +on(type: 'formUninstall', callback: Callback<string>): void 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 | 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<string> | Yes| Callback used to return the widget ID.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - let callback = function(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<string>): void +off(type: 'formUninstall', callback?: Callback<string>): void 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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | 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.
The value must be the same as that in **on("formUninstall")**.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| +| callback | Callback<string> | 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.
The value must be the same as that in **on('formUninstall')**.| **Example** ```ts -import formHost from '@ohos.application.formHost'; - let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } -formHost.off("formUninstall", callback); +formHost.off('formUninstall', callback); ``` ## notifyFormsVisible @@ -1005,12 +941,10 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous **Example** ```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) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).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 **Example** ```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) => { 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 **Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); ``` ## shareForm9+ @@ -1123,7 +1051,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>) 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 @@ -1138,13 +1066,11 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca **Example** ```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) => { 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 | -------- | -------- | | Promise<void> | Promise that returns no value.| -**Parameters** +**Example** ```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +let formId = '12400633174999288'; +let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); + console.log('formHost shareForm, error:' + JSON.stringify(error)); }); ``` ## notifyFormsPrivacyProtected9+ -notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean, callback: AsyncCallback<void>): void +notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void 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 | deviceId | string | Yes | Remote device ID.| ```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); + console.log('formHost shareForm, error:' + JSON.stringify(error)); }); ``` - -## 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<void> | 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)); -} -``` diff --git a/en/application-dev/reference/apis/js-apis-application-formProvider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md index 4d604ff7295eb9903d450bc96f9c00fde253ee11..d23e6e15e21e68017f0c305427ad095446ca54cf 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -1,10 +1,10 @@ -# @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. > **NOTE** > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> This module is deprecated since API version 9. You are advised to use [formProvider](js-apis-app-form-formProvider.md) instead. +> This module is deprecated since API version 9. You are advised to use [FormProvider](js-apis-app-form-formProvider.md) instead. ## Modules to Import @@ -31,13 +31,11 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback **Example** ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let formId = "12400633174999288"; + let formId = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { - if (error.code) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); - } + if (error.code) { + 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 **Example** ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let formId = "12400633174999288"; + let formId = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); }); ``` @@ -88,21 +84,19 @@ Updates a widget. This API uses an asynchronous callback to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts 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) => { - if (error.code) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + } }); ``` @@ -119,7 +113,7 @@ Updates a widget. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#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** @@ -131,14 +125,12 @@ Updates a widget. This API uses a promise to return the result. ```ts 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(() => { - console.log('formProvider updateForm success'); + console.log('formProvider updateForm success'); }).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 | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** ```ts -import formProvider from '@ohos.app.form.formProvider'; - formProvider.getFormsInfo((error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` ## getFormsInfo9+ @@ -182,24 +172,22 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** ```ts import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : 'entry' }; formProvider.getFormsInfo(filter, (error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + 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 | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| +| Promise<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| **Example** ```ts import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : 'entry' }; formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).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 | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"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<string> | Yes| Callback used to return the widget ID.| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; - import formProvider from '@ohos.app.form.formProvider'; let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + '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) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + 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 **Example** ```ts - import formProvider from '@ohos.app.form.formProvider'; - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + } }; formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + 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 | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"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** @@ -346,20 +329,18 @@ Requests to publish a widget to the widget host. This API uses a promise to retu **Example** ```ts - import formProvider from '@ohos.app.form.formProvider'; - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + } }; 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) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); }); ``` @@ -388,12 +369,12 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { } else { if (isSupported) { let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + } }; formProvider.requestPublishForm(want, (error, data) => { if (error.code) { @@ -429,12 +410,12 @@ Checks whether a widget can be published to the widget host. This API uses a pro formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: 'FormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + } }; formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); @@ -445,4 +426,4 @@ formProvider.isRequestPublishFormSupported().then((isSupported) => { }).catch((error) => { console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); }); -``` +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md index 17de66e19334dce9663017c3df9c18b575e14bd7..21501d5710ad7435acafbe8d66892d04b2f45da9 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -4,12 +4,12 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions, > **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 ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.application.missionManager'; ``` ## Required Permissions @@ -43,17 +43,17 @@ Registers a listener to observe the mission status. **Example** ```ts -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; -console.log("registerMissionListener") -var listenerid = missionManager.registerMissionListener(listener); +console.log('registerMissionListener'); +let listenerid = missionManager.registerMissionListener(listener); ``` @@ -79,21 +79,21 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** ```ts - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + console.log('registerMissionListener'); + let listenerid = missionManager.registerMissionListener(listener); 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 **Example** ```ts - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + console.log('registerMissionListener'); + let listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid).catch(function (err) { console.log(err); @@ -167,20 +167,15 @@ Obtains the information about a given mission. This API uses an asynchronous cal ```ts import missionManager from '@ohos.application.missionManager' - var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); - missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - if (error.code) { - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - - console.log("mission.missionId = " + mission.missionId); - console.log("mission.runningState = " + mission.runningState); - console.log("mission.lockedState = " + mission.lockedState); - console.log("mission.timestamp = " + mission.timestamp); - console.log("mission.label = " + mission.label); - console.log("mission.iconPath = " + mission.iconPath); + let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);}); + missionManager.getMissionInfo('', allMissions[0].missionId, (error, mission) => { + console.log('getMissionInfo is called, error.code = ' + error.code) + 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); }); ``` @@ -213,9 +208,9 @@ Obtains the information about a given mission. This API uses a promise to return **Example** ```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); }); ``` @@ -244,17 +239,13 @@ Obtains information about all missions. This API uses an asynchronous callback t **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - }) + 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)); + }); ``` @@ -286,9 +277,9 @@ Obtains information about all missions. This API uses a promise to return the re **Example** ```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); }); ``` @@ -317,27 +308,19 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback **Example** ```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) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - 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); - }) - }) + missionManager.getMissionSnapShot('', id, (error, snapshot) => { + console.log('getMissionSnapShot is called, error.code = ' + error.code); + 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 **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; - var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ + let snapshot = missionManager.getMissionSnapShot('', id).catch(function (err){ console.log(err); }); ``` @@ -407,27 +390,19 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr **Example** ```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) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - 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); - }) - }) + missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => { + console.log('getLowResolutionMissionSnapShot is called, error.code = ' + error.code); + console.log('bundleName = ' + snapshot.ability.bundleName); + }); + }); ``` @@ -459,17 +434,17 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ' + allMissions.length); + console.log('missions = ' + JSON.stringify(allMissions)); + let id = allMissions[0].missionId; - var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ + let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (err){ console.log(err); }); ``` @@ -497,20 +472,16 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + missionManager.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.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. **Example** ```ts - import missionManager from '@ohos.application.missionManager' - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + import missionManager from '@ohos.application.missionManager'; + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + 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); @@ -580,20 +551,16 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + missionManager.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.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. **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + 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); @@ -667,20 +634,16 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + missionManager.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.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 **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + 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); @@ -744,10 +707,10 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; 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. **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; missionManager.clearAllMissions().catch(function (err){ console.log(err); }); @@ -802,20 +765,16 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + missionManager.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.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 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | 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<void> | Yes| Callback used to return the result.| **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + missionManager.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.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 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | 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** @@ -891,15 +846,15 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + 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); diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index 5fc9b0999940310b10bf7b4e7227d5651153eb50..d83e3e55f645b38303b2d4252e60ce2181f54099 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -10,7 +10,7 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for ## Modules to Import ```ts -import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' +import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'; ``` ## StaticSubscriberExtensionAbility.onReceiveEvent @@ -27,17 +27,14 @@ Callback of the common event of a static subscriber. | 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** ```ts - var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") - { - onReceiveEvent(event){ - console.log('onReceiveEvent,event:' + event.code); - } - } - export default MyStaticSubscriberExtensionAbility - + class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event: ' + JSON.stringify(event)); + } + } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-testRunner.md b/en/application-dev/reference/apis/js-apis-application-testRunner.md index d2146524c0c5249374e21c95762438d35dc48c35..34d272091725be3a4086b6df466f02f4aff38e7c 100644 --- a/en/application-dev/reference/apis/js-apis-application-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -11,7 +11,7 @@ To implement your own unit test framework, extend this class and override its AP ## Modules to Import ```ts -import TestRunner from '@ohos.application.testRunner' +import TestRunner from '@ohos.application.testRunner'; ``` ## TestRunner.onPrepare @@ -27,7 +27,7 @@ Prepares the unit test environment to run test cases. ```ts export default class UserTestRunner implements TestRunner { onPrepare() { - console.log("Trigger onPrepare") + console.log('Trigger onPrepare'); } onRun() {} }; @@ -49,7 +49,7 @@ Runs test cases. export default class UserTestRunner implements TestRunner { onPrepare() {} onRun() { - console.log("Trigger onRun") + console.log('Trigger onRun'); } }; ``` diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index 44cc01a00c5057488b45a5a6a38cc02adbf1cbc2..bb546edc8038717b5f2f29208f5e864cbac7f338 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -4,7 +4,7 @@ Want is a carrier for information transfer between objects (application componen > **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 @@ -18,119 +18,117 @@ import Want from '@ohos.application.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | -| bundleName | string | No | Bundle name.| +| deviceId | string | No | ID of the device running the ability. | +| 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.| | 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).| -| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Array\ | 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). | +| 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:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| entities | Array\ | 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. | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** -- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). +- Basic usage ```ts let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry" // moduleName is optional. + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.extreme.test', + 'abilityName': 'MainAbility', + 'moduleName': 'entry' // moduleName is optional. }; this.context.startAbility(want, (error) => { // 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 ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { - keyForString: "str", + keyForString: 'str', }, - } + }; ``` * Number ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForInt: 100, keyForDouble: 99.99, }, - } + }; ``` * Boolean ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForBool: true, }, - } + }; ``` * Object ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { keyForObject: { - keyForObjectString: "str", + keyForObjectString: 'str', keyForObjectInt: -200, keyForObjectDouble: 35.5, keyForObjectBool: false, }, }, - } + }; ``` * Array ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.demo', + abilityName: 'com.example.demo.MainAbility', parameters: { - keyForArrayString: ["str1", "str2", "str3"], + keyForArrayString: ['str1', 'str2', 'str3'], keyForArrayInt: [100, 200, 300, 400], keyForArrayDouble: [0.1, 0.2], - keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + keyForArrayObject: [{obj1: 'aaa'}, {obj2: 100}], }, - } + }; ``` * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; let fd; try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } 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": "EntryAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} + '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} } }; this.context.startAbility(want, (error) => { // 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). - diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index db0814fa146e09114eeb4fa635dfa78564ee595e..126adb9256b7b2148c11c90e3301d1ada11c2fbc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -1,6 +1,6 @@ # 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 @@ -9,3 +9,26 @@ | onConnect7+ | function | Yes | Callback invoked when a connection is set up. | | onDisconnect7+ | function | Yes | Callback invoked when a connection is interrupted. | | onFailed7+ | 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); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index d6b0c51051feb92f30495bdc552f84cae5e06018..bed4cf0eeeb553d2e5674a53aa101f2cabef7c38 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -35,12 +35,12 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var mode = "rw"; -DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { - console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let mode = 'rwt'; +DAHelper.openFile('dataability:///com.example.DataAbility', mode, (err) => { + console.info('==========================>Called=======================>'); }); ``` @@ -69,12 +69,12 @@ Opens a file with a specified URI. This API uses a promise to return a file desc ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var mode = "rw"; -DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { - console.info("openFile data: " + JSON.stringify(data)); +let mode = 'rwt'; +DAHelper.openFile('dataability:///com.example.DataAbility', mode).then((data) => { + console.info('==========================>openFileCallback=======================>'); }); ``` @@ -98,15 +98,15 @@ Registers an observer to listen for changes in the data specified by a given URI ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let helper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); function onChangeNotify() { - console.info("onChangeNotify call back"); + console.info('==========================>onChangeNotify=======================>'); }; -DAHelper.on( - "dataChange", - "dataability:///com.example.DataAbility", +helper.on( + 'dataChange', + 'dataability:///com.example.DataAbility', onChangeNotify ); ``` @@ -131,20 +131,20 @@ Deregisters the observer that listens for changes in the data specified by a giv ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let helper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); function onChangeNotify() { - console.info("onChangeNotify call back"); + console.info('==========================>onChangeNotify=======================>'); }; -DAHelper.off( - "dataChange", - "dataability:///com.example.DataAbility", - onChangeNotify +helper.off( + 'dataChange', + 'dataability:///com.example.DataAbility', ); -DAHelper.off( - "dataChange", - "dataability:///com.example.DataAbility", +helper.off( + 'dataChange', + '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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { - console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.getType('dataability:///com.example.DataAbility', (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -199,11 +199,11 @@ Obtains the media resource type of the data specified by a given URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { - console.info("getType data: " + JSON.stringify(data)); +DAHelper.getType('dataability:///com.example.DataAbility').then((data) => { + console.info('==========================>getTypeCallback=======================>'); }); ``` @@ -227,14 +227,17 @@ Obtains the supported media resource types of a specified file. This API uses an ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { - console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', + 'image/*', (err, data) => { + console.info('==========================>Called=======================>'); }); ``` + + ## DataAbilityHelper.getFileTypes getFileTypes(uri: string, mimeTypeFilter: string): Promise\> @@ -260,11 +263,12 @@ Obtains the supported media resource types of a specified file. This API uses a ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { - console.info("getFileTypes data: " + JSON.stringify(data)); +DAHelper.getFileTypes('dataability:///com.example.DataAbility', + '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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { - console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.normalizeUri('dataability:///com.example.DataAbility', (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -319,11 +323,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { - console.info("normalizeUri data: " + JSON.stringify(data)); +DAHelper.normalizeUri('dataability:///com.example.DataAbility',).then((data) => { + console.info('=================>normalizeUriCallback=======================>'); }); ``` @@ -346,14 +350,16 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { - console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (err, data) => { + console.info('==========================>Called=======================>'); }); ``` + + ## DataAbilityHelper.denormalizeUri denormalizeUri(uri: string): Promise\ @@ -378,11 +384,11 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { - console.info("denormalizeUri data: " + JSON.stringify(data)); +DAHelper.denormalizeUri('dataability:///com.example.DataAbility',).then((data) => { + console.info('===============>denormalizeUriCallback=======================>'); }); ``` @@ -405,11 +411,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let helper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { - console.info("==========================>Called=======================>"); +helper.notifyChange('dataability:///com.example.DataAbility', (err) => { + console.info('==========================>Called=======================>'); }); ``` @@ -437,11 +443,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { - console.info("================>notifyChangeCallback================>"); +DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => { + console.info('================>notifyChangeCallback================>'); }); ``` @@ -465,17 +471,18 @@ Inserts a single data record into the database. This API uses an asynchronous ca ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, - "blobType": "u8", + 'name': 'rose', + 'age': 22, + 'salary': 200.5, + 'blobType': 'u8', }; -DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { - console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.insert('dataability:///com.example.DataAbility', valueBucket, + (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -504,17 +511,17 @@ Inserts a single data record into the database. This API uses a promise to retur ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const valueBucket = { - "name": "rose1", - "age": 221, - "salary": 20.5, - "blobType": "u8", + 'name': 'rose1', + 'age': 221, + 'salary': 20.5, + 'blobType': 'u8', }; -DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { - console.info("insert data: " + JSON.stringify(data)); +DAHelper.insert('dataability:///com.example.DataAbility', valueBucket).then((data) => { + console.info('====================>insertCallback=======================>'); }); ``` @@ -538,14 +545,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); -DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { - console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe12', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}); +DAHelper.batchInsert('dataability:///com.example.DataAbility', cars, + (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -574,14 +582,14 @@ Inserts multiple data records into the database. This API uses a promise to retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); -DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => { - console.info("batchInsert data: " + JSON.stringify(data)); +let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe12', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}); +DAHelper.batchInsert('dataability:///com.example.DataAbility', cars).then((data) => { + console.info('==================>batchInsertCallback=======================>'); }); ``` @@ -606,12 +614,13 @@ Deletes one or more data records from the database. This API uses an asynchronou ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => { - console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.delete('dataability:///com.example.DataAbility', da, + (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 ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { - console.info("delete data: " + JSON.stringify(data)); +DAHelper.delete('dataability:///com.example.DataAbility', da).then((data) => { + console.info('==========================>deleteCallback=======================>'); }); ``` @@ -672,18 +681,18 @@ Updates data records in the database. This API uses an asynchronous callback to ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": "u8", + 'name': 'roe1', + 'age': 21, + 'salary': 20.5, + 'blobType': 'u8', }; let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => { - console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.update('dataability:///com.example.DataAbility', va, da, (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -714,18 +723,18 @@ Updates data records in the database. This API uses a promise to return the resu ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": "u8", + 'name': 'roe1', + 'age': 21, + 'salary': 20.5, + 'blobType': 'u8', }; let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { - console.info("update data: " + JSON.stringify(data)); +DAHelper.update('dataability:///com.example.DataAbility', va, da).then((data) => { + console.info('==========================>updateCallback=======================>'); }); ``` @@ -751,13 +760,13 @@ Queries data in the database. This API uses an asynchronous callback to return t ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + '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(); -DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { - console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.query('dataability:///com.example.DataAbility', cars, da, (err, data) => { + console.info('==========================>Called=======================>'); }); ``` @@ -790,21 +799,21 @@ Queries data in the database. This API uses a promise to return the result. ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + '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(); -DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { - console.info("query data: " + JSON.stringify(data)); +DAHelper.query('dataability:///com.example.DataAbility', cars, da).then((data) => { + console.info('==========================>queryCallback=======================>'); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void +call(uri: string, method: string, arg: string, extras: PacMap): Promise\ -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 @@ -812,11 +821,16 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback | 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. | | arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** @@ -824,23 +838,20 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback import featureAbility from '@ohos.ability.featureAbility'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" -); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", - "method", "arg", {"key1":"value1"}, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + err); - return; - } + 'dataability:///com.example.jsapidemo.UserDataAbility'); +dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', + 'method', 'arg', {'key1':'value1'}).then((data) => { console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap): Promise\ +call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): 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 @@ -848,16 +859,11 @@ Calls an extended API of the DataAbility. This API uses a promise to return the | 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. | | arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | - -**Return value** - -| Type| Description| -|------ | ------- | -|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| +| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes | Callback used to return the result. | **Example** @@ -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'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" -); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", - "method", "arg", {"key1":"value1"}).then((data) => { + 'dataability:///com.example.jsapidemo.UserDataAbility'); +dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', + 'method', 'arg', {'key1':'value1'}, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + err); + return; + } console.info('Operation succeeded: ' + data); -}).catch((error) => { - console.error('Operation failed. Cause: ' + error); }); ``` @@ -887,7 +894,7 @@ Operates data in the database in batches. This API uses an asynchronous callback | 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. | | callback | AsyncCallback\> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. | @@ -899,9 +906,9 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" -); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { + 'dataability:///com.example.jsapidemo.UserDataAbility'); +dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', + op, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + err); return; @@ -922,7 +929,7 @@ Operates data in the database in batches. This API uses a promise to return the | 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. | **Return value** @@ -939,9 +946,9 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" -); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { + 'dataability:///com.example.jsapidemo.UserDataAbility'); +dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', + op).then((data) => { console.info('Operation succeeded: ' + data); }).catch((error) => { console.error('Operation failed. Cause: ' + error); diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 49b14bebedfaa76b495e8a127e3f4bd243c649b7..7f06d6f4a058efdf1be198126d5c9ef7f5e6f453 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -11,67 +11,64 @@ The **DataAbilityResult** module defines the operation result on DataAbilities. | 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. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; -// Perform database operations in batches. -function executeBatchOperation() { - let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); - let DAHelper; - try { - DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if (DAHelper == null) { - console.error('DAHelper is null'); - return; - } - } catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); +let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility'); +let DAHelper; +try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if (DAHelper == null) { + console.error('DAHelper is null'); return; } +} catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); + return; +} - let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, - }; - let operations = [ - { - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, - }, - { - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, - } - ]; +let valueBucket = { + 'name': 'DataAbilityHelperTest', + 'age': 24, + 'salary': 2024.20, +}; +let operations = [ +{ + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, +}, +{ + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, +} +]; - try { - DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { - for (let i = 0; i < data.length; i++) { - let dataAbilityResult = data[i]; - console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); - console.log('dataAbilityResult.count: ' + dataAbilityResult.count); - } - }).catch(err => { - console.error('executeBatch error: ' + JSON.stringify(err)); - }); - } catch (err) { +try { + let promise = DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { + for (let i = 0; i < data.length; i++) { + let dataAbilityResult = data[i]; + console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); + console.log('dataAbilityResult.count: ' + dataAbilityResult.count); + } + }).catch(err => { console.error('executeBatch error: ' + JSON.stringify(err)); - } + }); +} catch (err) { + console.error('executeBatch error: ' + JSON.stringify(err)); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index 71b8d529703d28e01072d8f18f92ebe30b82c556..b9101bf4c71f419096bf9031ab243824190dac66 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -16,31 +16,29 @@ The **StartAbilityParameter** module defines the parameters for starting an abil **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; let Want = { - bundleName: "com.example.abilityStartSettingApp2", - abilityName: "com.example.abilityStartSettingApp.EntryAbility", -} + bundleName: 'com.example.abilityStartSettingApp2', + abilityName: 'com.example.abilityStartSettingApp.MainAbility', +}; let abilityStartSetting ={ [featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400], [featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] : featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, -} +}; let startAbilityParameter = { want : Want, abilityStartSetting : abilityStartSetting -} +}; -try { - featureAbility.startAbility(startAbilityParameter, (err, data) => { - console.log('errCode : ' + JSON.stringify(err)); - console.log('data : ' + JSON.stringify(data)); - }); +featureAbility.startAbility(startAbilityParameter, (err, data)=>{ + console.log('errCode : ' + JSON.stringify(err)); + console.log('data : ' + JSON.stringify(data)); } catch(error) { - console.log("startAbility error: " + JSON.stringify(error)); + console.log('startAbility error: ' + JSON.stringify(error)); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index afb331b3fc2cb610025dd741e94abe0392fe4a5b..10cb9e144dacdee13674168aad28eadabc63f635 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -4,21 +4,21 @@ Want is a carrier for information transfer between objects (application componen > **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 | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | -| bundleName | string | No | Bundle name.| +| deviceId | string | No | ID of the device running the ability. | +| 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.| | 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). | -| 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). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Array\ | 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). | +| 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:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| entities | Array\ | 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. | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** @@ -27,42 +27,42 @@ Want is a carrier for information transfer between objects (application componen ```ts let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry" // moduleName is optional. + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.extreme.test', + 'abilityName': 'MainAbility', + 'moduleName': 'entry' // moduleName is optional. }; this.context.startAbility(want, (error) => { // 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): ```ts - import fileio from '@ohos.fileio'; + import fileio from '@ohos.fileio';; // ... let fd; try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } 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": "EntryAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} + '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} } }; this.context.startAbility(want, (error) => { // 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) + }); // ... ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md index ec729194807c24ea49b7b117cb308628c031a75a..22da49708e973f844aa7a5f206b88ceb9db9102a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -14,9 +14,9 @@ The **Context** object is created in a **featureAbility** and returned through i ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -import bundle from '@ohos.bundle.bundleManager'; -var context = featureAbility.getContext(); +import bundle from '@ohos.bundle'; +let context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ - console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + context.verifyPermission('com.example.permission', {uid:datainfo.uid}, (err, data) =>{ + console.info('verifyPermission err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data)); }); }); ``` -For details about **getBundleInfo** in the sample code, see [bundleManager](js-apis-bundleManager.md). @@ -125,9 +124,9 @@ Verifies whether the current PID and UID have the given permission. This API use ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -context.verifyPermission("com.example.permission", (err, data) =>{ - console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let context = featureAbility.getContext(); +context.verifyPermission('com.example.permission', (err, 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var Permission = {pid:1}; +let context = featureAbility.getContext(); +let Permission = {pid:1}; 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( - ["com.example.permission1", - "com.example.permission2", - "com.example.permission3", - "com.example.permission4", - "com.example.permission5"], + ['com.example.permission1', + 'com.example.permission2', + 'com.example.permission3', + 'com.example.permission4', + 'com.example.permission5'], 1, (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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( - ["com.example.permission1", - "com.example.permission2", - "com.example.permission3", - "com.example.permission4", - "com.example.permission5"], + ['com.example.permission1', + 'com.example.permission2', + 'com.example.permission3', + 'com.example.permission4', + 'com.example.permission5'], 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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\ | Yes | Callback used to return the display orientation. | **Example** @@ -458,10 +457,10 @@ Sets the display orientation for this ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation=bundle.DisplayOrientation.UNSPECIFIED 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 | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | +| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | | Promise\ | Promise used to return the display orientation. | **Example** @@ -485,10 +484,10 @@ Sets the display orientation for this ability. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation=bundle.DisplayOrientation.UNSPECIFIED 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show=true 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show=true 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp=true 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp=true 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 | 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** ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext().getApplicationContext(); +let context = featureAbility.getContext().getApplicationContext(); ``` ## Context.isUpdatingConfigurations7+ @@ -1196,9 +1195,9 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.printDrawnCompleted((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 ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); 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) => { | requestCode | Read-only | number | Yes | Request code passed.| | permissions | Read-only | Array\ | Yes | Permissions requested. | | authResults | Read-only | Array\ | Yes | Permission request result. | - -## AppVersionInfo7+ - -**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.| diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 351d6ad145824d0eba37a3a1eadc846034763c97..8127343de9a7723ab1f293c9b846fca4426d8dd4 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -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. > **NOTE** -> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs of this module can be used only in the FA model. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -19,10 +17,13 @@ The **ProcessInfo** module defines process information. You can use [getProcessI ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo((err, data) => { - console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); - let pid = data.pid; - let processName = data.processName; + if (err.code !== 0) { + console.info('getProcessInfo err: ' + JSON.stringify(err) + 'data: ' + JSON.stringify(data)); + let pid = data.pid; + let processName = data.processName; + } }); ``` + diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index ad4f7e19a9fd40b82684c0acc11a458073bbb16b..94782760127cc17c7c94f1d64e4afd486d93e3ee 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -35,20 +35,20 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 - Example ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var timeout = 100; +let abilityDelegator; +let timeout = 100; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { - console.info("waitAbilityMonitor promise"); + console.info('waitAbilityMonitor promise'); }); ``` @@ -307,10 +307,10 @@ Obtains the application context. **Example** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); -var context = abilityDelegator.getAppContext(); +let context = abilityDelegator.getAppContext(); ``` @@ -338,15 +338,15 @@ Obtains the lifecycle state of an ability. **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; - var state = abilityDelegator.getAbilityState(ability); - console.info("getAbilityState" + state); + let state = abilityDelegator.getAbilityState(ability); + console.info('getAbilityState' + state); }); ``` @@ -369,12 +369,12 @@ Obtains the top ability of this application. This API uses an asynchronous callb **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; }); ``` @@ -398,12 +398,12 @@ Obtains the top ability of this application. This API uses a promise to return t **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility().then((data : any) => { - console.info("getCurrentTopAbility promise"); + console.info('getCurrentTopAbility promise'); ability = data; }); ``` @@ -428,15 +428,15 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts -var abilityDelegator; -var want = { - bundleName: "bundleName", - abilityName: "abilityName" +let abilityDelegator; +let want = { + bundleName: 'bundleName', + abilityName: 'abilityName' }; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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. **Example** ```ts -var abilityDelegator; -var want = { - bundleName: "bundleName", - abilityName: "abilityName" +let abilityDelegator; +let want = { + bundleName: 'bundleName', + abilityName: 'abilityName' }; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; 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 **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; 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 **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; 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 **Example** ```ts -var abilityDelegator; -var ability; +let abilityDelegator; +let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; 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. **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.printSync(msg); @@ -665,12 +665,12 @@ Prints log information to the unit test console. This API uses an asynchronous c **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; +let abilityDelegator; +let cmd = 'cmd'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +let abilityDelegator; +let cmd = 'cmd'; +let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var cmd = "cmd"; -var timeout = 100; +let abilityDelegator; +let cmd = 'cmd'; +let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var msg = "msg"; +let abilityDelegator; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; +let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); 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 **Example** ```ts -var abilityDelegator; -var timeout = 100; +let abilityDelegator; +let timeout = 100; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} +let monitor = { + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => { - console.info("waitAbilityStageMonitor callback"); + console.info('waitAbilityStageMonitor callback'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index a5f131c3e02071f3d55cbfdc73955ffef42889d3..e95c4595831162018344c4c4fad168a8657c4d56 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -1,6 +1,6 @@ # 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** > @@ -28,5 +28,5 @@ Describes the ability delegator arguments. ```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; -var args = AbilityDelegatorRegistry.getArguments(); +let args = AbilityDelegatorRegistry.getArguments(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index d8726205b8caec547f270e8efe6472e37cd99eb4..0e9b919995d16daf58aa0f73da236cf1e809aa04 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -19,6 +19,7 @@ Describes an ability monitor. | Name | Type | Readable| Writable| Description | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | | 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.
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.
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.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| @@ -30,19 +31,22 @@ Describes an ability monitor. **Example** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', + moduleName: "moduleName", onAbilityCreate: onAbilityCreateCallback -} +}; -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { - console.info("addAbilityMonitor callback"); + console.info('addAbilityMonitor callback'); }); ``` + + diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 62b1f7e1fae204f2e6b1f6dcdc76521da3c51777..01bf2d71fd84273aa9080b9be842ea81112e6eb8 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -30,15 +30,15 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( ```ts 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)); for (let i = 0; i < data.length; i++) { let abilityinfo = data[i]; - console.log("abilityinfo.ability: " + JSON.stringify(abilityinfo.ability)); - console.log("abilityinfo.pid: " + JSON.stringify(abilityinfo.pid)); - console.log("abilityinfo.uid: " + JSON.stringify(abilityinfo.uid)); - console.log("abilityinfo.processName: " + JSON.stringify(abilityinfo.processName)); - console.log("abilityinfo.startTime: " + JSON.stringify(abilityinfo.startTime)); - console.log("abilityinfo.abilityState: " + JSON.stringify(abilityinfo.abilityState)); + console.log('abilityinfo.ability: ' + JSON.stringify(abilityinfo.ability)); + console.log('abilityinfo.pid: ' + JSON.stringify(abilityinfo.pid)); + console.log('abilityinfo.uid: ' + JSON.stringify(abilityinfo.uid)); + console.log('abilityinfo.processName: ' + JSON.stringify(abilityinfo.processName)); + console.log('abilityinfo.startTime: ' + JSON.stringify(abilityinfo.startTime)); + console.log('abilityinfo.abilityState: ' + JSON.stringify(abilityinfo.abilityState)); } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 79f750797c12bfd9c323e2f613650c016ea2930b..aa037839a646d9a78f7317934464ca0824606afd 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -1,6 +1,6 @@ # 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. @@ -28,5 +28,5 @@ class MyAbilityStage extends AbilityStage { | 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.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index 76a4ae2e425ce91acb0f79d22889cba231809c26..9605509b0e1c7c64c379d7da92656467cdc568ca 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -11,15 +11,15 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta **Example** ```ts -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; let monitor = { - moduleName: "feature_as1", - srcEntrance: "./ets/Application/MyAbilityStage.ts", + moduleName: 'feature_as1', + srcEntrance: './ets/Application/MyAbilityStage.ts', }; let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { - console.info("stageMonitor waitAbilityStageMonitor, abilityStage = " + JSON.stringify(data)); + console.info('stageMonitor waitAbilityStageMonitor, abilityStage = ' + JSON.stringify(data)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md index c281c62ff040c74bdc84def40b9db824ce95492a..08909d57aaf7557b88b3c8e7c34fb24ca9333a75 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -4,32 +4,24 @@ The **AppStateData** module defines the application state data, which can be obt **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 | | ------------------------- | ------ | ---- | --------- | | bundleName8+ | string | No | Bundle name.| | uid8+ | number | No | UID of the application. | -| state8+ | number | No | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| +| state8+ | number | No | Application state.| **Example** - ```ts -import appManager from "@ohos.app.ability.appManager" +import appManager from "@ohos.application.appManager"; -function getForegroundAppInfos() { - appManager.getForegroundApplications((error, data) => { - if (error && error.code) { - console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - for (let i = 0; i < data.length; i++) { - let appStateData = data[i]; - console.log('appStateData.bundleName: ' + appStateData.bundleName); - console.log('appStateData.uid: ' + appStateData.uid); - console.log('appStateData.state: ' + appStateData.state); - } - }); -} +appManager.getForegroundApplications((error, data) => { + for (let i = 0; i < data.length; i++) { + let appStateData = data[i]; + console.info('appStateData.bundleName: ' + appStateData.bundleName); + console.info('appStateData.uid: ' + appStateData.uid); + console.info('appStateData.state: ' + appStateData.state); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 73b2a329f018d64bf93ac8f64ece86792e4eff59..c5a1d36e8abd645fbb7d9db63982b0babfe7c980 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -15,9 +15,9 @@ Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContex 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. @@ -27,6 +27,7 @@ Registers a listener to monitor the ability lifecycle of the application. | 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.| **Return value** @@ -40,56 +41,56 @@ Registers a listener to monitor the ability lifecycle of the application. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); let AbilityLifecycleCallback = { onAbilityCreate(ability) { - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityCreate ability:' + ability); }, onWindowStageCreate(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageCreate ability:' + ability); + console.log('AbilityLifecycleCallback onWindowStageCreate windowStage:' + windowStage); }, onWindowStageActive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageActive ability:' + ability); + console.log('AbilityLifecycleCallback onWindowStageActive windowStage:' + windowStage); }, onWindowStageInactive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageInactive ability:' + ability); + console.log('AbilityLifecycleCallback onWindowStageInactive windowStage:' + windowStage); }, onWindowStageDestroy(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageDestroy ability:' + ability); + console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage:' + windowStage); }, onAbilityDestroy(ability) { - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityDestroy ability:' + ability); }, onAbilityForeground(ability) { - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityForeground ability:' + ability); }, onAbilityBackground(ability) { - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityBackground ability:' + ability); }, onAbilityContinue(ability) { - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityContinue ability:' + ability); } } // 1. Obtain applicationContext through the context attribute. let applicationContext = this.context.getApplicationContext(); // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback); + console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId)); } } ``` -## ApplicationContext.unregisterAbilityLifecycleCallback +## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback) -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. @@ -99,6 +100,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | +| type | 'abilityLifecycle' | Yes | Event type.| | callbackId | number | Yes | ID of the listener to deregister.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -107,22 +109,53 @@ Deregisters the listener that monitors the ability lifecycle of the application. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + console.log('stage applicationContext: ' + applicationContext); + applicationContext.off(type: 'abilityLifecycle', lifecycleId, (error, data) => { + 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. @@ -132,6 +165,7 @@ Registers a listener for system environment changes. This API uses an asynchrono | 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.| **Return value** @@ -145,32 +179,32 @@ Registers a listener for system environment changes. This API uses an asynchrono ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate') globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ - console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + console.log('onConfigurationUpdated config:' + JSON.stringify(config)); }, onMemoryLevel(level){ - console.log("onMemoryLevel level:" + level); + console.log('onMemoryLevel level:' + level); } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + callbackId = applicationContext.on('environment', EnvironmentCallback); + console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId)); } } ``` -## ApplicationContext.unregisterEnvironmentCallback +## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback) -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. @@ -180,6 +214,7 @@ Deregisters the listener for system environment changes. This API uses an asynch | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | +| type | 'environment' | Yes | Event type.| | callbackId | number | Yes | ID of the listener to deregister. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -188,14 +223,154 @@ Deregisters the listener for system environment changes. This API uses an asynch ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + applicationContext.off('environment', callbackId, (error, data) => { + 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.getRunningProcessInformation9+ + +getRunningProcessInformation(): Promise\>; + +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\> | 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.getRunningProcessInformation9+ + +getRunningProcessInformation(callback: AsyncCallback\>): 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\> | 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.killProcessesBySelf9+ + +killProcessesBySelf(): Promise; + +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\> | 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.killProcessesBySelf9+ + +killProcessesBySelf(callback: AsyncCallback); + +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\ | 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)); + } +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index e6d3137582ee3b485e4a342a4a5a3b6b5473ed32..baa8975bb76e62b6aea7bb4dac067a46b6dbc8bd 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -16,7 +16,7 @@ The **ApplicationStateObserver** module defines an observer to listen for applic **Example** ```ts -import appManager from "@ohos.application.appManager" +import appManager from "@ohos.application.appManager"; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { @@ -34,6 +34,6 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData)); } -} +}; let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md index 3c0e5e3806181cbff0492cfe4faa387f315e516b..208e363227aaf20c6bac05ab0b6837ea74656adb 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -19,10 +19,10 @@ Take the stage model as an example. You can access the **stageMode** field throu ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -class EntryAbility extends UIAbility { +class MainAbility extends UIAbility { onCreate(want, launchParam) { - // EntryAbility onCreate, isStageMode: true - console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode); + // MainAbility onCreate, isStageMode: true + console.log('MainAbility onCreate, isStageMode: ' + this.context.stageMode); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index 068ec63b234762aa017a03a6ba40ceb84038b170..339eb62bd54fb97a121081b5691a6166c643a022 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -49,7 +49,7 @@ Creates the context based on the bundle name. **Example** ```ts -let bundleContext = this.context.createBundleContext("com.example.test"); +let bundleContext = this.context.createBundleContext('com.example.test'); ``` ## Context.createModuleContext @@ -75,9 +75,11 @@ Creates the context based on the module name. **Example** ```ts -let moduleContext = this.context.createModuleContext("entry"); +let moduleContext = this.context.createModuleContext('entry'); ``` +## Context.createModuleContext + createModuleContext(bundleName: string, moduleName: string): Context; 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** ```ts -let moduleContext = this.context.createModuleContext("com.example.test", "entry"); +let moduleContext = this.context.createModuleContext('com.example.test', 'entry'); ``` ## Context.getApplicationContext diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb..03d9db491f12e36244dd83828e66380fda2ecafd 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -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). -## ContinueCallback.onContinueDone - -onContinueDone(result: number): void; - -Called when the mission continuation is complete. - **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | result | number | No| Mission continuation result.| +| Name | Type | Readable | Writable | Description | +| --------------------- | -------- | ---- | ---- | ------------------ | +| onContinueDone | function | Yes | No | Mission continuation result. | **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager' + import distributedMissionManager from '@ohos.distributedMissionManager'; let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: '123', + dstDeviceId: '456', + missionId: 123, + wantParam: { + 'key':'value' + } }; let continueCallback = { @@ -37,10 +29,9 @@ Called when the mission continuation is complete. }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error && error.code) { - console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - } - console.log('continueMission finished'); + if (error.code != 0) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + console.info('continueMission finished') }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index 5582132e3f610a76175cbb73796b6283498c4395..06f98fe304de1d9474123995ad9c8e384640532d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -14,15 +14,15 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager' + import distributedMissionManager from '@ohos.distributedMissionManager'; let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: '123', + dstDeviceId: '456', + missionId: 123, + wantParam: { + 'key':'value' + } }; let continueCallback = { @@ -32,10 +32,9 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error && error.code) { - console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - } - console.log('continueMission finished'); + if (error.code != 0) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + console.info('continueMission finished') }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 271f2697803dde9d0b3f78c3bb661a03d925b95e..9ee22f675c5ce1430ab9d33bc2577f9e1b3fd27f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -1,8 +1,8 @@ # 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; @@ -19,18 +19,12 @@ Called when an unhandled exception occurs in the JS runtime. **Example** ```ts -import errorManager from '@ohos.app.ability.errorManager' +import errorManager from '@ohos.application.errorManager'; let observer = { onUnhandledException(errorMsg) { - console.log('HXW onUnhandledException, errorMsg: ', errorMsg); + console.log('onUnhandledException, errorMsg: ' + JSON.stringify(errorMsg)); } -} - -try { - errorManager.on("error", observer); -} catch (error) { - console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); -} +}; +errorManager.registerErrorObserver(observer); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index 8b580177c7622b33b0d2c06749a928e825ae84bc..a5939795a24ba0314109b81018b4e93d381334e6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -9,18 +9,16 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri ## 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 -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - eventFunc(){ - console.log("eventFunc is called"); +import Ability from '@ohos.application.Ability'; +export default class MainAbility extends Ability { + func1(){ + console.log('func1 is called'); } - onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc); + this.context.eventHub.on('123', this.func1); } } ``` @@ -41,36 +39,33 @@ Subscribes to an event. | callback | Function | Yes| Callback invoked when the event is triggered.| **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 off(event: string, callback?: Function): void; -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. +Unsubscribes from an event. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -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.| **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 @@ -121,26 +115,25 @@ Triggers an event. | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| **Example** - -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc); - // Result - // eventFunc is called,undefined,undefined - this.context.eventHub.emit("myEvent"); - // Result - // eventFunc is called,1,undefined - this.context.eventHub.emit("myEvent", 1); - // Result - // eventFunc is called,1,2 - this.context.eventHub.emit("myEvent", 1, 2); - } - - eventFunc(argOne, argTwo) { - console.log("eventFunc is called," + argOne + "," + argTwo); - } -} -``` + + ```ts + import Ability from '@ohos.application.Ability'; + + export default class MainAbility extends Ability { + onForeground() { + this.context.eventHub.on('123', this.func1); + // Result + // func1 is called,undefined,undefined + this.context.eventHub.emit('123'); + // Result + // func1 is called,1,undefined + this.context.eventHub.emit('123', 1); + // Result + // func1 is called,1,2 + this.context.eventHub.emit('123', 1, 2); + } + func1(a, b) { + console.log('func1 is called,' + a + ',' + b); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index a855d9577c9ef364caa7436a89983ca58d320d3c..ce0a916f3c17e8aeb02955b96d32d5ed50e2105f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -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. ```ts -import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' -import Want from '@ohos.application.Want' +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'; +import Want from '@ohos.application.Want'; export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { console.log('ServiceAbility onCreate, want: ' + want.abilityName); @@ -61,15 +61,14 @@ export default class TheServiceExtension extends ServiceExtension { Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. ```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { +import Ability from '@ohos.app.ability.Ability'; +export default class MainAbility extends Ability { onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate"); + console.log('[Demo] MainAbility onCreate'); let wantExt = { - deviceId: "", - bundleName: "com.example.TheServiceExtension", - abilityName: "TheServiceExtension", + deviceId: '', + bundleName: 'com.example.TheServiceExtension', + abilityName: 'TheServiceExtension', }; this.context.startServiceExtensionAbility(wantExt); } @@ -84,29 +83,29 @@ export default class ServiceModel { constructor() {} executeTask() { - if (globalThis.ExtensionContext == undefined) { - console.log("ERROR, ServiceExtension does not exist"); + if (globalThis.ExtensionContext === undefined) { + console.log('ERROR, ServiceExtension does not exist'); return; } - var moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; + let moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; this.moduleName = moduleInfo.name; // Execute service logic based on the module name, which differentiates devices with different performance. switch (this.moduleName) { - case "highPerformance": - console.log("This is high performance device."); + case 'highPerformance': + console.log('This is high performance device.'); // Execute the corresponding service logic. break; - case "midPerformance": - console.log("This is mid performance device."); + case 'midPerformance': + console.log('This is mid performance device.'); // Execute the corresponding service logic. break; - case "lowPerformance": - console.log("This is low performance device."); + case 'lowPerformance': + console.log('This is low performance device.'); // Execute the corresponding service logic. break; default: - console.log("ERROR, invalid moduleName."); + console.log('ERROR, invalid moduleName.'); break; } } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 9485de9efd0dc76d78a905725fb742225b50340f..8121aeba926224edc8bedf7864c943920624596d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -5,7 +5,7 @@ The **ExtensionRunningInfo** module encapsulates ExtensionAbility running inform > **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. -> - 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 @@ -17,37 +17,29 @@ Import the **abilityManager** module and obtain the ExtensionAbility running inf | 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.| | uid | number | Yes| No| UID of the application.| | processName | string | Yes| No| Process name.| | startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| | clientPackage | Array<String> | 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** ```ts -import abilityManager from '@ohos.app.ability.abilityManager' - -var upperLimit = 1; -function getExtensionInfos() { - abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { - if (error && error.code) { - console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - - for (let i = 0; i < data.length; i++) { - let extensionRunningInfo = data[i]; - console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); - console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); - 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)); - } - }); -} +import abilityManager from '@ohos.application.abilityManager'; +let upperLimit = 1; +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { + console.log('getExtensionRunningInfos err: ' + err + ' data: ' + JSON.stringify(data)); + for (let i = 0; i < data.length; i++) { + let extensionRunningInfo = data[i]; + 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)); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index d888ccdc51bef996937e9d2e6ef891980ffe457c..9444e1aae0fe77a44f5f453fe679864e2f24846f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -16,19 +16,18 @@ Before using the **ServiceExtensionContext** module, you must first obtain a **F ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; - export default class MyFormExtensionAbility extends FormExtensionAbility { - onAddForm(want) { - let formContext = this.context; // Obtain a FormExtensionContext instance. - // ... - let dataObj1 = { - temperature: "11c", - "time": "11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -}; + onAddForm() { + let formContext = this.context; // »ñÈ¡FormExtensionContext + // ... + let dataObj1 = { + temperature:'11c', + 'time':'11:00' + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} ``` ## startAbility @@ -51,29 +50,23 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts -import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; - -export default class MyFormExtensionAbility extends FormExtensionAbility { - onFormEvent(formId, message) { - // Call startAbility() when the message event is triggered. - console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); - let want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "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'); - } - }); - } +let want = { + deviceId: '', + bundleName: 'com.example.formstartability', + abilityName: 'MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: {} }; +this.context.startAbility(want, (error, data) => { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log(`FormExtensionContext startAbility success`); + } +}); ``` ## startAbility @@ -96,30 +89,24 @@ Starts an ability. This API uses a promise to return the result. | Type | Description | | ------------ | ---------------------------------- | -| Promise<void> | Promise that returns no value.| +| Promise<void< | Promise that returns no value.| **Example** ```ts -import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; - -export default class MyFormExtensionAbility extends FormExtensionAbility { - onFormEvent(formId, message) { - // Call startAbility() when the message event is triggered. - console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); - let want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "EntryAbility", - parameters: { - "message": message - } - }; - this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); - }).catch((error) => { - console.info("StartAbility failed"); - }); - } +let want = { + deviceId: '', + bundleName: 'com.example.formstartability', + abilityName: 'MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: {} }; +this.context.startAbility(want).then(() => { + console.info('StartAbility Success'); +}).catch((error) => { + console.info('StartAbility failed'); +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md index 7ccae03fa363d0850338d07f1318a377f10fc293..99005e97f90b0216c329fcaae2062d12adc1c026 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md @@ -15,19 +15,19 @@ The **MissionCallback** module defines the callbacks invoked after synchronizati import distributedMissionManager from '@ohos.distributedMissionManager'; let missionDeviceInfo = { - deviceId: "123456" + deviceId: '123456' }; let missionCallback = { notifyMissionsChanged: function (deviceId) { - console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + console.log('notifyMissionsChanged deviceId: ' + JSON.stringify(deviceId)); }, notifySnapshot: function (deviceId, mission) { - console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); - console.log("notifySnapshot mission: " + JSON.stringify(mission)); + console.log('notifySnapshot deviceId: ' + JSON.stringify(deviceId)); + console.log('notifySnapshot mission: ' + JSON.stringify(mission)); }, notifyNetDisconnect: function (deviceId, state) { - console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); - console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + console.log('notifyNetDisconnect deviceId: ' + JSON.stringify(deviceId)); + console.log('notifyNetDisconnect state: ' + JSON.stringify(state)); } }; distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md index 9157fc697346087895870a5bbd6e4a0368d6bde7..aa59e7a78842e43536274ae28b58c4df8b26f34b 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md @@ -13,19 +13,19 @@ The **MissionDeviceInfo** module defines the parameters required for registering import distributedMissionManager from '@ohos.distributedMissionManager'; let missionDeviceInfo = { - deviceId: "123456" + deviceId: '123456' }; let missionCallback = { notifyMissionsChanged: function (deviceId) { - console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + console.log('notifyMissionsChanged deviceId: ' + JSON.stringify(deviceId)); }, notifySnapshot: function (mission, deviceId) { - console.log("notifySnapshot mission: " + JSON.stringify(mission)); - console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + console.log('notifySnapshot mission: ' + JSON.stringify(mission)); + console.log('notifySnapshot deviceId: ' + JSON.stringify(deviceId)); }, notifyNetDisconnect: function (mission, state) { - console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); - console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + console.log('notifyNetDisconnect mission: ' + JSON.stringify(mission)); + console.log('notifyNetDisconnect state: ' + JSON.stringify(state)); } }; distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index afefb70c5a3e0b0059e4712992c3f736516bc2f7..1aabfc19619a5e5c41f2fdf1d60dada4104f8868 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -19,27 +19,16 @@ The **MissionInfo** module defines detailed information about a mission. The inf **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.application.missionManager'; -try { - missionManager.getMissionInfo("", 1, (error, data) => { - if (error.code) { - // Process service logic errors. - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - - console.log('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); - console.log('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); - console.log('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); - console.log('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); - console.log('getMissionInfo want is:' + JSON.stringify(data.want)); - console.log('getMissionInfo label is:' + JSON.stringify(data.label)); - console.log('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); - console.log('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); - }); -} catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); -} +missionManager.getMissionInfo('12345', 1, (error, data) => { + console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); + console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); + console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); + console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); + console.info('getMissionInfo want is:' + JSON.stringify(data.want)); + console.info('getMissionInfo label is:' + JSON.stringify(data.label)); + console.info('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); + console.info('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index a9f9e6cf9540c02ada58ea7e89f76b9c9c297efb..3af1f92ce0ada364d0928af3ab85ef3d5b9cfdbc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -1,6 +1,6 @@ # 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 @@ -16,32 +16,27 @@ The **MissionListener** module defines the listeners used to observe the mission **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.application.missionManager'; let listener = { onMissionCreated: function (mission) { - console.log("onMissionCreated mission: " + JSON.stringify(mission)); + console.log('onMissionCreated mission: ' + JSON.stringify(mission)); }, onMissionDestroyed: function (mission) { - console.log("onMissionDestroyed mission: " + JSON.stringify(mission)); + console.log('onMissionDestroyed mission: ' + JSON.stringify(mission)); }, onMissionSnapshotChanged: function (mission) { - console.log("onMissionSnapshotChanged mission: " + JSON.stringify(mission)); + console.log('onMissionSnapshotChanged mission: ' + JSON.stringify(mission)); }, onMissionMovedToFront: function (mission) { - console.log("onMissionMovedToFront mission: " + JSON.stringify(mission)); + console.log('onMissionMovedToFront mission: ' + JSON.stringify(mission)); }, onMissionIconUpdated: function (mission, icon) { - console.log("onMissionIconUpdated mission: " + JSON.stringify(mission)); + console.log('onMissionIconUpdated mission: ' + JSON.stringify(mission)); }, onMissionClosed: function (mission) { - console.log("onMissionClosed mission: " + JSON.stringify(mission)); + console.log('onMissionClosed mission: ' + JSON.stringify(mission)); } }; - -try { - let listenerId = missionManager.on("mission", listener); -} catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); -} +let listenerid = missionManager.registerMissionListener(listener); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md index 9e2e2aa23a6589c0eb80075f8de60f65261e6903..e88556a10417f6f2ec824744c46ddf2c44f97460 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -15,14 +15,14 @@ The **MissionParameter** module defines the parameters required for mission sync import distributedMissionManager from '@ohos.distributedMissionManager'; let missionParameter = { - deviceId: "123456", + deviceId: '123456', fixConflict: true, tag: 123 }; try { distributedMissionManager.startSyncRemoteMissions(missionParameter, (err, data) => { - console.log("startSyncRemoteMissions, data: " + JSON.stringify(data)); + console.log('startSyncRemoteMissions, data: ' + JSON.stringify(data)); } ); } catch (err) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index a97f3b32b71f90078cb03f32fa46262f5cf6b770..cee807663fe7e45ceb04de308aecb90e18aacc2c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -20,33 +20,19 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** **Example** ```ts - import ElementName from '@ohos.bundle'; - import image from '@ohos.multimedia.image'; - import missionManager from '@ohos.app.ability.missionManager'; - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); - return; - } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (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); - } +import ElementName from '@ohos.bundle'; +import image from '@ohos.multimedia.image'; +import missionManager from '@ohos.application.missionManager'; + +missionManager.getMissionInfos('', 10, (error, missions) => { + console.log('getMissionInfos is called, error.code = ' + error.code); + 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); + }); +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index ae6beb1357d9d25dfcd06cbcd1d65df660fa44bb..d17c505d3f2566a75e5ba13b3f44c75e8179d5a1 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -17,7 +17,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; let context = undefined; - class EntryAbility extends ServiceExtensionAbility { + class MainAbility extends ServiceExtensionAbility { onCreate() { context = this.context; // Obtain a ServiceExtensionContext instance. } @@ -68,9 +68,9 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; try { @@ -141,11 +141,11 @@ Starts an ability. This API uses a promise to return the result. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { windowMode: 0, }; @@ -212,12 +212,12 @@ Starts an ability with the start options specified. This API uses an asynchronou **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var options = { + let options = { windowMode: 0 }; @@ -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: - 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). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -290,12 +290,12 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -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: - 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). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -367,13 +367,13 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -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: - 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). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -453,13 +453,13 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -518,10 +518,10 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -584,10 +584,10 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -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. -**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 @@ -650,12 +650,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -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. -**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 @@ -721,12 +721,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) @@ -780,10 +780,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -843,10 +843,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -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. -**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 @@ -905,12 +905,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -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. -**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 @@ -973,12 +973,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId) @@ -1118,17 +1118,17 @@ Connects this ability to a ServiceAbility. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } - } + }; - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { @@ -1178,19 +1178,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { @@ -1214,7 +1214,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Number returned after **connectAbility** is called.| +| connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.| | callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1232,7 +1232,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous ```ts // connection is the return value of connectServiceExtensionAbility. - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection, (error) => { @@ -1266,7 +1266,7 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Number returned after **connectAbility** is called.| +| connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.| **Return value** @@ -1288,8 +1288,8 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret **Example** ```ts - // connection is the return value of connectAbility. - var connection = 1; + // connection is the return value of connectServiceExtensionAbility. + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) @@ -1317,8 +1317,8 @@ Starts an ability in the foreground or background and obtains the caller object Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + - 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). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1355,14 +1355,14 @@ Observe the following when using this API: Start an ability in the background. ```ts - var caller = undefined; + let caller = undefined; // Start an ability in the background by not passing parameters. - var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "" + let wantBackground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'MainAbility', + deviceId: '' }; try { @@ -1386,16 +1386,16 @@ Observe the following when using this API: Start an ability in the foreground. ```ts - var caller = undefined; - - // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. - var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "", + let caller = undefined; + + // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true. + let wantForeground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'MainAbility', + deviceId: '', parameters: { - "ohos.aafwk.param.callAbilityToForeground": true + 'ohos.aafwk.param.callAbilityToForeground': true } }; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 51b10659d38d55686ced548c624798d77391f102..fede94a87e55f92c1264c99002f33c5bd3598c55 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -19,13 +19,13 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio **Example** ```ts -import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; let abilityDelegator; -let cmd = "cmd"; +let cmd = 'cmd'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info("executeShellCommand callback, result: ", err); - console.info("executeShellCommand callback, data: ", data); + console.info('executeShellCommand callback, failed: ', err); + console.info('executeShellCommand callback, success: ', data); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 91cdb18e7b4cc9563cecaf27cc125d3108d649e6..563a039ac724ef9a6e92708b3971573709336d16 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -66,9 +66,9 @@ Observe the following when using this API: **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; try { @@ -138,12 +138,12 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var options = { + let options = { windowMode: 0 }; @@ -218,11 +218,11 @@ Observe the following when using this API: **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { windowMode: 0, }; @@ -295,10 +295,10 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -310,7 +310,7 @@ Observe the following when using this API: return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + + console.log('startAbilityForResult succeed, result.resultCode = ' + result.resultCode) }); } catch (paramError) { @@ -371,12 +371,12 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var options = { + let options = { windowMode: 0, }; @@ -389,7 +389,7 @@ Observe the following when using this API: return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + + console.log('startAbilityForResult succeed, result.resultCode = ' + result.resultCode) }); } catch (paramError) { @@ -457,11 +457,11 @@ Observe the following when using this API: **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { windowMode: 0, }; @@ -469,7 +469,7 @@ Observe the following when using this API: this.context.startAbilityForResult(want, options) .then((result) => { // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); + console.log('startAbilityForResult succeed, result.resultCode = ' + result.resultCode); }) .catch((error) => { // Process service logic errors. @@ -531,12 +531,12 @@ Starts an ability with the account ID specified. This API uses an asynchronous c **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { 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 return; } // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' + result.resultCode) }); } catch (paramError) { @@ -607,13 +607,13 @@ Starts an ability with the start options and account ID specified. This API uses **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -626,7 +626,7 @@ Starts an ability with the start options and account ID specified. This API uses return; } // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' + result.resultCode) }); } catch (paramError) { @@ -691,13 +691,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -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) .then((result) => { // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + console.log('startAbilityForResultWithAccount succeed, result.resultCode = ' + result.resultCode) }) .catch((error) => { @@ -756,10 +756,10 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -816,10 +816,10 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result. **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -877,12 +877,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -942,12 +942,12 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) @@ -1000,10 +1000,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -1057,10 +1057,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; try { @@ -1119,12 +1119,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { @@ -1181,12 +1181,12 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId) @@ -1315,13 +1315,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe **Example** ```ts - var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + let want = { + bundleName: 'com.extreme.myapplication', + abilityName: 'SecondAbility' } - var resultCode = 100; + let resultCode = 100; // AbilityResult information returned to the caller. - var abilityResult = { + let abilityResult = { want, resultCode } @@ -1380,13 +1380,13 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe **Example** ```ts - var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + let want = { + bundleName: 'com.extreme.myapplication', + abilityName: 'SecondAbility' } - var resultCode = 100; + let resultCode = 100; // AbilityResult information returned to the caller. - var abilityResult = { + let abilityResult = { want, resultCode } @@ -1445,18 +1445,18 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { @@ -1509,19 +1509,19 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { @@ -1568,7 +1568,7 @@ Disconnects a connection. This API uses a promise to return the result. ```ts // connection is the return value of connectServiceExtensionAbility. - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) @@ -1620,7 +1620,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r ```ts // connection is the return value of connectServiceExtensionAbility. - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection, (error) => { @@ -1670,14 +1670,14 @@ Observe the following when using this API: Start an ability in the background. ```ts - var caller = undefined; + let caller = undefined; // Start an ability in the background by not passing parameters. - var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "" + let wantBackground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'MainAbility', + deviceId: '' }; try { @@ -1701,16 +1701,16 @@ Observe the following when using this API: Start an ability in the foreground. ```ts - var caller = undefined; - - // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. - var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "", + let caller = undefined; + + // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true. + let wantForeground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'MainAbility', + deviceId: '', 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 **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { @@ -1855,13 +1855,13 @@ Starts an ability with the account ID specified. This API uses an asynchronous c **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -1932,13 +1932,13 @@ Starts an ability with the account ID specified. This API uses a promise to retu **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + let want = { + deviceId: '', + bundleName: 'com.extreme.test', + abilityName: 'MainAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -1978,7 +1978,7 @@ Requests permissions from the user by displaying a dialog box. This API uses an **Example** ```ts - var permissions=['com.example.permission'] + let permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions,(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 **Example** ```ts - var permissions=['com.example.permission'] + let permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions).then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { @@ -2037,7 +2037,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call **Example** ```ts - this.context.setMissionLabel("test",(result) => { + this.context.setMissionLabel('test',(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 **Example** ```ts - this.context.setMissionLabel("test").then(() => { + this.context.setMissionLabel('test').then(() => { console.log('success'); }).catch((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 ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2140,9 +2140,9 @@ Sets an icon for this ability in the mission. This API uses a promise to return ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2180,7 +2180,7 @@ Restores the window stage data for this ability. **Example** ```ts - var storage = new LocalStorage(); + let storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -2201,6 +2201,6 @@ Checks whether this ability is in the terminating state. **Example** ```ts - var isTerminating = this.context.isTerminating(); + let isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index 5ca299f0ad5f9df4f5b460b30e9e34c7dad82d5d..bdd437754a4024a8b414db11cce5a3ed9887b326 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -6,7 +6,7 @@ The **TriggerInfo** module defines the information required for triggering the W | Name | Type | Mandatory| Description | | ---------- | --- |-------------------- | ----------- | -| code | number | Yes | Custom result code provided for the target WantAgent.| +| code | number | Yes | Result code.| | want | Want | No | Want. | | permission | string | No | Permission. | | extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 8facc43fc842570c3eb0ea95a141bdaa77dcf252..289a5ebef3d8095fd599e630e0236935551246d1 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -7,7 +7,7 @@ The **WantAgentInfo** module defines the information required for triggering a * | Name | Type | Mandatory| Description | | -------------- | ------------------------------- | ---- | ---------------------- | | wants | Array\ | 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.| | 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. | diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 6657eb3e558732fa50af4c7bb82f7b26e3457433..2a33aae1dcb790fe1ba811c606c70286574c7e44 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,4 +1,4 @@ -# @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. @@ -160,8 +160,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } 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 let wantAgentInfo = { @@ -192,12 +199,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getBundleName callback -function getBundleNameCallback(err, data) { - console.info('==========================>getBundleNameCallback=======================>'); -} -WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -261,10 +262,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getBundleName(wantAgent).then((data) => { - console.info('==========================>getBundleNameCallback=======================>'); + if (wantAgent) { + WantAgent.getBundleName(wantAgent).then((data) => { + console.info('==========================>getBundleNameCallback=======================>'); + }); + } }); ``` @@ -300,8 +302,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } 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 let wantAgentInfo = { @@ -332,12 +341,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getUid callback -function getUidCallback(err, data) { - console.info('==========================>getUidCallback=======================>'); -} -WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -402,10 +405,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getUid(wantAgent).then((data) => { - console.info('==========================>getUidCallback=======================>'); + if (wantAgent) { + WantAgent.getUid(wantAgent).then((data) => { + console.info('==========================>getUidCallback=======================>'); + }); + } }); ``` @@ -440,8 +444,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } 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 let wantAgentInfo = { @@ -472,12 +483,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// cancel callback -function cancelCallback(err, data) { - console.info('==========================>cancelCallback=======================>'); -} -WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -542,10 +547,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.cancel(wantAgent).then((data) => { - console.info('==========================>cancelCallback=======================>'); + if (wantAgent) { + WantAgent.cancel(wantAgent).then((data) => { + console.info('==========================>cancelCallback=======================>'); + }); + } }); ``` @@ -582,8 +588,19 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } 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 let wantAgentInfo = { @@ -614,16 +631,6 @@ let wantAgentInfo = { } 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) { wantAgent1 = data; wantAgent2 = data; } 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 let wantAgentInfo = { @@ -693,12 +707,6 @@ let wantAgentInfo = { } 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) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; + if (data) { + WantAgent.equal(wantAgent1, wantAgent2).then((data) => { + console.info('==========================>equalCallback=======================>'); + }); + } }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { @@ -827,11 +840,12 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + if (data) { + WantAgent.getOperationType(wantAgent, (OperationType) => { + console.log('----------- getOperationType ----------, OperationType: ' + OperationType); + }) + } }); - -WantAgent.getOperationType(wantAgent, (OperationType) => { - console.log('----------- getOperationType ----------, OperationType: ' + OperationType); -}) ``` ## WantAgent.getOperationType9+ @@ -901,7 +915,6 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { }); ``` - ## WantAgentFlags **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -940,5 +953,5 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { | info | WantAgent | Yes | A triggered **WantAgent** object. | | want | Want | Yes | An existing triggered **want**. | | 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. |