diff --git a/CODEOWNERS b/CODEOWNERS index 677e3bcd63ef928fbabf68ebc2ac1a6597a93571..025c30e10317662d65ab6b1d45688bf87ef41817 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -24,11 +24,16 @@ zh-cn/device-dev/driver/ @li-yan339 zh-cn/device-dev/get-code/ @li-yan339 zh-cn/device-dev/hpm-part/ @duangavin123_admin zh-cn/device-dev/reference/hdi-apis/ @li-yan339 -zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 +zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin @@ -46,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 +zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23 diff --git a/README_zh.md b/README_zh.md index 3c65434aac3acaee899db2e1eba85e61c03de5a5..ebf1bc8d7557d35f99eaacf8fd1427972d61d3b0 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,7 +18,7 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta1版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta1.md)了解版本详情。 + - OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 5b61bcec4b25312f994ed94362339e601df5cd55..e1d67a295b673453d7340fb20a40c81d8c7a7855 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -78,29 +78,29 @@ To create Page abilities for an application in the stage model, you must impleme onCreate(want, launchParam) { console.log("MainAbility onCreate") } - + onDestroy() { console.log("MainAbility onDestroy") } - + onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - + windowStage.loadContent("pages/index").then((data) => { console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) }).catch((error) => { console.error("MainAbility load content failed with error: " + JSON.stringify(error)) }) } - + onWindowStageDestroy() { console.log("MainAbility onWindowStageDestroy") } - + onForeground() { console.log("MainAbility onForeground") } - + onBackground() { console.log("MainAbility onBackground") } @@ -300,7 +300,7 @@ export default class MainAbility extends Ability { Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI. ```ts -import router from '@system.router' +import router from '@ohos.router' @Entry @Component diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 753b706605487dbe2cf5ebe0ce961b19d94e7ee0..e60f2c01333c1bef7324b3ef6cfe2c83821a95cd 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -54,8 +54,10 @@ To make you better understand how functions work together and jumpstart your app API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. They are organized as follows: + +- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) + - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) - Native APIs diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 09bc3b733346db921cd04b76aff04b41d60af0b9..34d2d1b19aea81ee810c472b7ffaf297b0478091 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -292,7 +292,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md). ``` - var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}; + var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); ``` 2. Format the relative time.
diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 30bb3aacd85d9e11012fb66dc276a88476139126..f2ee2ee4ab190bcd3487aaca974a153c0aed914e 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,9 +1,9 @@ # Development References -- [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md) -- [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md) +- [Component Reference(TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) +- [Component Reference(JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [APIs](apis/Readme-EN.md) - + - [JS (eTS Included) APIs](apis/Readme-EN.md) - Native APIs - [Standard Library](native-lib/third_party_libc/musl.md) diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md new file mode 100644 index 0000000000000000000000000000000000000000..2a7827180ffe1c0a0d5aa022957eb90a0d6cb3f9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -0,0 +1,266 @@ +# AbilityManager + +The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +# Modules to Import + +```js +import AbilityManager from '@ohos.application.abilityManager' +``` + +## AbilityState + +Enumerates the ability states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | + +## updateConfiguration + +updateConfiguration(config: Configuration, callback: AsyncCallback\): void + +Updates the configuration. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config, () => { + console.log('------------ updateConfiguration -----------'); +}) +``` + +## updateConfiguration + +updateConfiguration(config: Configuration): Promise\ + +Updates the configuration. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success'); +}).catch((err) => { + console.log('updateConfiguration fail'); +}) +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(callback: AsyncCallback\>): void + +Obtains the ability 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 | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(): Promise\> + +Obtains the ability running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +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** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +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. + +**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** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var upperLimit = 0; + +abilitymanager.getExtensionRunningInfos(upperLimit).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\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +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\| Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +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-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 185338803c92789aea72fa0fca2ab7791ab89ea1..94182ce2915f60bd6998f512d17288920549d3f8 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,17 +1,15 @@ # ApplicationInfo +The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **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. -Provides the application information. - ## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Application name. | @@ -26,16 +24,19 @@ Provides the application information. | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | supportedModes | number | Yes | No | Running modes supported by the application. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | | entryDir | string | Yes | No | Path for storing application files. | | codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application. | -| metadata9+ | Map\> | Yes | No | Metadata of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| +| metadata9+ | Map\> | Yes | No | Metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| | removable8+ | boolean | Yes | No | Whether the application is removable. | | accessTokenId8+ | number | Yes | No | Access token ID of the application. | | uid8+ | number | Yes | No | UID of the application. | | entityType8+ | string | Yes | No | Entity type of the application. | -| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.| +| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT**.| +| iconResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Icon resource of the application.| +| labelResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Label resource of the application.| +| descriptionResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application.| | appDistributionType9+ | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. | | appProvisionType9+ | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**.| diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 93ab553ef10e531fea0b2d0871b65183d22bf6fa..8c27495f208ad620ed6e104fb19c958350805c1e 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,11 +1,22 @@ # Device Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **DeviceManager** module provides APIs for distributed device management. + +System applications can call the APIs to do the following: + +- Subscribe to or unsubscribe from device state changes. +- Discover peripheral untrusted devices. +- Authenticate or deauthenticate a device. +- Query the trusted device list. +- Query local device information, including the device name, type, and ID. + +> **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 are system APIs and cannot be called by third-party applications. -## Modules to import: +## Modules to Import ``` import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -21,10 +32,10 @@ Creates a **DeviceManager** instance. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the application.| - | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes| Callback invoked to return the **DeviceManager** instance created.| + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------------------------------------ | + | bundleName | string | Yes | Bundle name of an application. | + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| - Example ``` @@ -34,10 +45,40 @@ Creates a **DeviceManager** instance. return; } console.info("createDeviceManager success"); - this.dmInstance = data; + let dmInstance = data; }); ``` +## DeviceInfo + +Defines device information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ---------------------- | ------------------------- | ---- | -------- | +| deviceId | string | Yes | Unique identifier of a device.| +| deviceName | string | Yes | Device name. | +| deviceType | [DeviceType](#devicetype) | Yes | Device type. | +| networkId8+ | string | Yes | Network ID of the device. | + + +## DeviceType + +Enumerates the device types. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ------------ | ---- | ---- | +| SPEAKER | 0x0A | Smart speaker.| +| PHONE | 0x0E | Phone. | +| TABLET | 0x11 | Tablet. | +| WEARABLE | 0x6D | Wearable.| +| TV | 0x9C | Smart TV. | +| CAR | 0x83 | Car. | +| UNKNOWN_TYPE | 0 | Unknown device type.| + ## DeviceStateChangeAction @@ -45,42 +86,103 @@ Enumerates the device states. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Default Value| Description| -| -------- | -------- | -------- | -| ONLINE | 0 | The device is online.| -| READY | 1 | The device is ready, and the device information has been synchronized.| -| OFFLINE | 2 | The device is offline.| -| CHANGE | 3 | The device information is changed.| +| Name | Default Value | Description | +| ------- | ---- | --------------- | +| ONLINE | 0 | The device is online. | +| READY | 1 | The device is ready, and the device information has been synchronized.| +| OFFLINE | 2 | The device is offline. | +| CHANGE | 3 | The device information is changed. | +## SubscribeInfo -## DeviceType +Defines subscription information. -Enumerates the device types. +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ------------- | --------------------------------- | ---- | ----------------- | +| subscribeId | number | Yes | Subscription ID, used to identify a device discovery period.| +| mode | [DiscoverMode ](#discovermode) | No | Device discovery mode. | +| medium | [ExchangeMedium](#exchangemedium) | No | Medium used for device discovery. | +| freq | [ExchangeFreq](#exchangefreq) | No | Frequency of device discovery. | +| isSameAccount | boolean | No | Whether the same account is used on the discovered device. | +| isWakeRemote | boolean | No | Whether to wake up the discovered device. | +| capability | [SubscribeCap](#subscribecap) | No | Discovery capability. | + + +## DiscoverMode + +Enumerates the device discovery modes. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Default Value| Description| -| -------- | -------- | -------- | -| SPEAKER | 0x0A | Smart speaker.| -| PHONE | 0x0E | Phone.| -| TABLET | 0x11 | Tablet.| -| WEARABLE | 0x6D | Wearable.| -| TV | 0x9C | Smart TV.| -| CAR | 0x83 | Car.| -| UNKNOWN_TYPE | 0 | Unknown device type.| +| Name | Default Value | Description | +| --------------------- | ---- | ----- | +| DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.| +| DISCOVER_MODE_ACTIVE | 0xAA | Active discovery.| -## DeviceInfo +## ExchangeMedium -Defines device information. +Enumerates the media used for device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | number | Yes| Unique device identifier.| -| deviceName | string | Yes| Device name.| -| deviceType | number | Yes| Device type.| +| Name | Default Value | Description | +| ---- | ---- | --------- | +| AUTO | 0 | Automatic. | +| BLE | 1 | Bluetooth. | +| COAP | 2 | Wi-Fi.| +| USB | 3 | USB. | + +## ExchangeFreq + +Enumerates the device discovery frequencies. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ---------- | ---- | ----- | +| LOW | 0 | Low frequency. | +| MID | 1 | Medium frequency. | +| HIGH | 2 | High frequency. | +| SUPER_HIGH | 3 | Ultra-high frequency.| + + +## SubscribeCap + +Enumerates the discovery capabilities. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ------------------------- | ---- | -------------- | +| SUBSCRIBE_CAPABILITY_DDMP | 0 | DDMP capability. This will be deprecated later.| +| SUBSCRIBE_CAPABILITY_OSD | 1 | OSD capability. | + + +## AuthParam + +Defines the authentication parameters. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| extraInfo | {[key:string] : any} | No | Extended field.| + +## AuthInfo + +Defines authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| token | number | Yes | Authentication token. | +| extraInfo | {[key:string] : any} | No | Extended field.| ## DeviceManager @@ -92,12 +194,12 @@ Provides APIs to obtain information about trusted devices and local devices. Bef release(): void -Releases the **DeviceManager** instance that is no longer used. +Releases this **DeviceManager** instance when it is no longer used. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Example - ``` + ```js dmInstance.release(); ``` @@ -111,16 +213,258 @@ Obtains all trusted devices synchronously. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | -------------------------------------- | --------- | | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| - Example - ``` + ```js var deviceInfoList = dmInstance.getTrustedDeviceListSync(); ``` +### getTrustedDeviceList8+ + +getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): void + +Obtains all trusted devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------- | + | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList((err, data) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + console.log('get trusted device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getTrustedDeviceList8+ + +getTrustedDeviceList(): Promise<Array<DeviceInfo>> + +Obtains all trusted devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + }); + ``` + +### getLocalDeviceInfoSync8+ + +getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) + +Obtains local device information synchronously. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Name | Description | + | -------------------------------------- | --------- | + | Array<[DeviceInfo](#deviceinfo)> | List of local devices obtained.| + +- Example + ```js + var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + ``` + + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void + +Obtains local device information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------- | + | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo((err, data) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + console.log('get local device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(): Promise<DeviceInfo> + +Obtains local device information. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + }); + ``` + +### startDeviceDiscovery + +startDeviceDiscovery(subscribeInfo: SubscribeInfo): void + +Starts to discover peripheral devices. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + +- Example + ```js + // Automatically generate a unique subscription ID. + var subscribeId = Math.floor(Math.random() * 10000 + 1000); + var subscribeInfo = { + "subscribeId": subscribeId, + "mode": 0xAA, // Active discovery + "medium": 0, // Automatic. Multiple media can be used for device discovery. + "freq": 2, // High frequency + "isSameAccount": false, + "isWakeRemote": false, + "capability": 1 + }; + dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + ``` + +### stopDeviceDiscovery + +stopDeviceDiscovery(subscribeId: number): void + +Stops device discovery. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ----------- | ------ | ---- | ----- | + | subscribeId | number | Yes | Subscription ID.| + +- Example + ```js + // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. + dmInstance.stopDeviceDiscovery(subscribeId); + ``` + +### authenticateDevice + +authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void + +Authenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | + | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | + | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + +- Example + ```js + // Information about the device to authenticate. The information can be obtained from the device discovery result. + var deviceInfo ={ + "deviceId": "XXXXXXXX", + "deviceName": "", + deviceType: 0x0E + }; + let authParam = { + "authType": 1, // Authentication type. The value 1 means no account PIN authentication. + "extraInfo": {} + } + dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { + if (err) { + console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); + token = data.pinToken; + }); + ``` + +### unAuthenticateDevice8+ + +unAuthenticateDevice(deviceInfo: DeviceInfo): void + +Deauthenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ------------------------- | ---- | ----- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + +- Example + ```js + dmInstance.unAuthenticateDevice(deviceInfo); + ``` + + +### verifyAuthInfo + +verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void + +Verifies authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------- | + | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | + | authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + +- Example + ```js + let authInfo = { + "authType": 1, + "token": xxxxxx, + "extraInfo": {} + } + dmInstance.verifyAuthInfo(authInfo, (err, data) => { + if (err) { + console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + }); + ``` + + ### on('deviceStateChange') on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -130,13 +474,13 @@ Subscribes to changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **deviceStateChange**, which indicates a device state change event.| - | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes| Callback invoked to return the device information and state.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state. | - Example - ``` + ```js dmInstance.on('deviceStateChange', (data) => { console.info("deviceStateChange on:" + JSON.stringify(data)); } @@ -146,20 +490,20 @@ Subscribes to changes in the device state. ### off('deviceStateChange') -off(type: 'deviceStateChange', callback?: Call back<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void +off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void Unsubscribes from changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **deviceStateChange** indicates an event of device state change.| - | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes| Callback invoked to return the device information and state.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| - Example - ``` + ```js dmInstance.off('deviceStateChange', (data) => { console.info('deviceStateChange' + JSON.stringify(data)); } @@ -167,6 +511,95 @@ Unsubscribes from changes in the device state. ``` +### on('deviceFound') + +on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Subscribes to device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| + | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | + +- Example + ```js + dmInstance.on('deviceFound', (data) => { + console.info("deviceFound:" + JSON.stringify(data)); + } + ); + ``` + +### off('deviceFound') + +off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Unsubscribes from device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used for device discovery, which is invoked to return the device information and state.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + +### on('discoverFail') + +on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void + +Subscribes to device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | + +- Example + ```js + dmInstance.on('discoverFail', (data) => { + this.log("discoverFail on:" + JSON.stringify(data)); + } + ); + ``` + +### off('discoverFail') + +off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void + +Unsubscribes from device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + + ### on('serviceDie') on(type: 'serviceDie', callback: () => void): void @@ -176,13 +609,13 @@ Subscribes to dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| - | callback | () => void | Yes| Callback invoked when a dead event of the **DeviceManager** service occurs.| + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. | - Example - ``` + ```js dmInstance.on("serviceDie", () => { console.info("serviceDie on"); } @@ -199,13 +632,13 @@ Unsubscribes from dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| - | callback | () => void | No| Callback used to return the dead event of the **DeviceManager** service.| + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | No | Callback used to return the dead event of the **DeviceManager** service. | - Example - ``` + ```js dmInstance.off("serviceDie", () => { console.info("serviceDie off"); } diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 01a012065ab52ac2e7a1dc781b608ec865394c31..d08cc7aafb9e16ecd89533e4a772c18372d23da5 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -8,8 +8,7 @@ Location services provide basic functions such as GNSS positioning, network posi ## Modules to Import - -``` +```js import geolocation from '@ohos.geolocation'; ``` @@ -23,7 +22,8 @@ Registers a listener for location changes with a location request initiated. **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| @@ -31,9 +31,9 @@ Registers a listener for location changes with a location request initiated. | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -52,16 +52,17 @@ Unregisters the listener for location changes with the corresponding location re **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -81,18 +82,19 @@ Registers a listener for location service status change events. **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| -- Example +**Example** - ``` + ```js var locationServiceState = (state) => { - console.log('locationServiceState: ' + state); + console.log('locationServiceState: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); ``` @@ -108,18 +110,19 @@ Unregisters the listener for location service status change events. **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| | callback | Callback<boolean> | No| Callback used to return the location service status change event.| -- Example +**Example** - ``` + ```js var locationServiceState = (state) => { - console.log('locationServiceState: state: ' + state); + console.log('locationServiceState: state: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); geolocation.off('locationServiceState', locationServiceState); @@ -136,7 +139,8 @@ Registers a listener for cached GNSS location reports. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| @@ -144,11 +148,11 @@ Registers a listener for cached GNSS location reports. | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| -- Example +**Example** - ``` + ```js var cachedLocationsCb = (locations) => { - console.log('cachedGnssLocationsReporting: locations: ' + locations); + console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); @@ -165,18 +169,19 @@ Unregisters the listener for cached GNSS location reports. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| -- Example +**Example** - ``` + ```js var cachedLocationsCb = (locations) => { - console.log('cachedGnssLocationsReporting: locations: ' + locations); + console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); @@ -194,18 +199,19 @@ Registers a listener for GNSS satellite status change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| -- Example +**Example** - ``` + ```js var gnssStatusCb = (satelliteStatusInfo) => { - console.log('gnssStatusChange: ' + satelliteStatusInfo); + console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); ``` @@ -221,17 +227,18 @@ Unregisters the listener for GNSS satellite status change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| -- Example +**Example** - ``` + ```js var gnssStatusCb = (satelliteStatusInfo) => { - console.log('gnssStatusChange: ' + satelliteStatusInfo); + console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); geolocation.off('gnssStatusChange', gnssStatusCb); @@ -248,18 +255,19 @@ Registers a listener for GNSS NMEA message change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| -- Example +**Example** - ``` + ```js var nmeaCb = (str) => { - console.log('nmeaMessageChange: ' + str); + console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb ); ``` @@ -275,18 +283,19 @@ Unregisters the listener for GNSS NMEA message change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| -- Example +**Example** - ``` + ```js var nmeaCb = (str) => { - console.log('nmeaMessageChange: ' + str); + console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb); geolocation.off('nmeaMessageChange', nmeaCb); @@ -303,7 +312,8 @@ Registers a listener for status change events of the specified geofence. **System capability**: SystemCapability.Location.Location.Geofence -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| @@ -311,52 +321,29 @@ Registers a listener for status change events of the specified geofence. | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| -- Example +**Example** - ``` - import WantAgent from '@ohos.wantAgent'; - import { OperationType, WantAgentFlags } from '@ohos.wantagent'; - // WantAgent object - var wantAgent; - // getWantAgent callback - function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } - } - // WantAgentInfo object - var wantAgentInfo = { + ```js + import geolocation from '@ohos.geolocation'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } } ], - operationType: OperationType.START_ABILITIES, + operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] - } - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; - geolocation.on('fenceStatusChange', requestInfo, wantAgent); + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); + }); ``` @@ -370,60 +357,91 @@ Unregisters the listener for status change events of the specified geofence. **System capability**: SystemCapability.Location.Location.Geofence -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| | request | GeofenceRequest | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| -- Example +**Example** - ``` - import WantAgent from '@ohos.wantAgent'; - import { OperationType, WantAgentFlags } from '@ohos.wantagent'; - // WantAgent object - var wantAgent; - // getWantAgent callback - function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } - } - // WantAgentInfo object - var wantAgentInfo = { + ```js + import geolocation from '@ohos.geolocation'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } } ], - operationType: OperationType.START_ABILITIES, + operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); + geolocation.off('fenceStatusChange', requestInfo, wantAgentObj); + }); + ``` + + +## geolocation.on('countryCodeChange')9+ + +on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; + +Subscribe to country code information reporting events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | + | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | + + +**Example** + + ```js + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geolocation.on('countryCodeChange', callback); + ``` + + +## geolocation.off('countryCodeChange')9+ + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; + +Unsubscribe from the country code to report events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | + | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | + + +**Example** + + ```js + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); } - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; - geolocation.on('fenceStatusChange', requestInfo, wantAgent); - geolocation.off('fenceStatusChange', requestInfo, wantAgent); + geolocation.on('countryCodeChange', callback); + geolocation.off('countryCodeChange', callback); ``` @@ -438,18 +456,24 @@ Obtains the current location. This API uses an asynchronous callback to return t **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { - console.log('locationChanger: ' + err + 'data: ' + location); + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } }; geolocation.getCurrentLocation(requestInfo, locationChange); geolocation.getCurrentLocation(locationChange); @@ -467,22 +491,24 @@ Obtains the current location. This API uses a promise to return the result. **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<[Location](#location)> | Promise used to return the current location.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - locationEventListener.getCurrentLocation(requestInfo).then((result) => { + geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); }); ``` @@ -498,17 +524,23 @@ Obtains the previous location. This API uses an asynchronous callback to return **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the previous location.| -- Example +**Example** - ``` + ```js geolocation.getLastLocation((err, data) => { - console.log('getLastLocation: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getLastLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getLastLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -523,15 +555,16 @@ Obtains the previous location. This API uses a promise to return the result. **System capability**: SystemCapability.Location.Location.Core -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<[Location](#location)> | Promise used to return the previous location.| -- Example +**Example** - ``` + ```js geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -549,17 +582,22 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.isLocationEnabled((err, data) => { - console.log('isLocationEnabled: ' + err + " data: " + data); + if (err) { + console.log('isLocationEnabled: err=' + JSON.stringify(err)); + } + if (data) { + console.log('isLocationEnabled: data=' + JSON.stringify(data)); + } }); ``` @@ -574,14 +612,15 @@ Checks whether the location service is enabled. This API uses a promise to retur **System capability**: SystemCapability.Location.Location.Core -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| -- Example +**Example** - ``` + ```js geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + result); }); @@ -599,17 +638,22 @@ Requests to enable the location service. This API uses an asynchronous callback **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.requestEnableLocation((err, data) => { - console.log('requestEnableLocation: ' + err + " data: " + data); + if (err) { + console.log('requestEnableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('requestEnableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -624,17 +668,17 @@ Requests to enable the location service. This API uses a promise to return the r **System capability**: SystemCapability.Location.Location.Core -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + result); + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); ``` @@ -645,23 +689,28 @@ enableLocation(callback: AsyncCallback<boolean>) : void; Enables the location service. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.enableLocation((err, data) => { - console.log('enableLocation: ' + err + " data: " + data); + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('enableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -672,23 +721,23 @@ enableLocation() : Promise<boolean> Enables the location service. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.enableLocation().then((result) => { - console.log('promise, enableLocation: ' + result); + console.log('promise, enableLocation: ' + JSON.stringify(result)); }); ``` @@ -698,23 +747,28 @@ disableLocation(callback: AsyncCallback<boolean>) : void; Disables the location service. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.disableLocation((err, data) => { - console.log('disableLocation: ' + err + " data: " + data); + if (err) { + console.log('disableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('disableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -725,23 +779,23 @@ disableLocation() : Promise<boolean> Disables the location service. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.disableLocation().then((result) => { - console.log('promise, disableLocation: ' + result); + console.log('promise, disableLocation: ' + JSON.stringify(result)); }); ``` @@ -755,17 +809,22 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| - -- Example +**Example** - ``` + ```js geolocation.isGeoServiceAvailable((err, data) => { - console.log('isGeoServiceAvailable: ' + err + " data: " + data); + if (err) { + console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); + } + if (data) { + console.log('isGeoServiceAvailable: data=' + JSON.stringify(data)); + } }); ``` @@ -780,22 +839,21 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **System capability**: SystemCapability.Location.Location.Geocoder -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| - -- Example +**Example** - ``` + ```js geolocation.isGeoServiceAvailable().then((result) => { - console.log('promise, isGeoServiceAvailable: ' + result); + console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); ``` - ## geolocation.getAddressesFromLocation getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void @@ -806,18 +864,24 @@ Converts coordinates into geographic description through reverse geocoding. This **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| -- Example +**Example** - ``` + ```js var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - console.log('getAddressesFromLocation: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -832,19 +896,21 @@ Converts coordinates into geographic description through reverse geocoding. This **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| -- Example +**Example** - ``` + ```js var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -862,19 +928,24 @@ Converts geographic description into coordinates through geocoding. This API use **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| - -- Example +**Example** - ``` + ```js var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { - console.log('getAddressesFromLocationName: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocationName: data=' + JSON.stringify(data)); + } }); ``` @@ -889,19 +960,21 @@ Converts geographic description into coordinates through geocoding. This API use **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| -- Example +**Example** - ``` + ```js var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -909,7 +982,6 @@ Converts geographic description into coordinates through geocoding. This API use ``` - ## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; @@ -920,16 +992,22 @@ Obtains the number of cached GNSS locations. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | -- Example +**Example** - ``` + ```js geolocation.getCachedGnssLocationsSize((err, size) => { - console.log('getCachedGnssLocationsSize: err:' + err + " size: " + size); + if (err) { + console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); + } + if (size) { + console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size)); + } }); ``` @@ -944,16 +1022,17 @@ Obtains the number of cached GNSS locations. **System capability**: SystemCapability.Location.Location.Gnss -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of cached GNSS locations.| -- Example +**Example** - ``` + ```js geolocation.getCachedGnssLocationsSize().then((result) => { - console.log('promise, getCachedGnssLocationsSize: ' + result); + console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); ``` @@ -968,16 +1047,22 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.flushCachedGnssLocations((err, result) => { - console.log('flushCachedGnssLocations: err:' + err + " result: " + result); + if (err) { + console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); + } + if (result) { + console.log('flushCachedGnssLocations: result=' + JSON.stringify(result)); + } }); ``` @@ -992,16 +1077,17 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **System capability**: SystemCapability.Location.Location.Gnss -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.flushCachedGnssLocations().then((result) => { - console.log('promise, flushCachedGnssLocations: ' + result); + console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); ``` @@ -1016,18 +1102,24 @@ Sends an extended command to the location subsystem. This API can only be called **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | command | LocationCommand | Yes| Extended command (string) to be sent.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { - console.log('sendCommand: err:' + err + " result: " + result); + if (err) { + console.log('sendCommand: err=' + JSON.stringify(err)); + } + if (result) { + console.log('sendCommand: result=' + JSON.stringify(result)); + } }); ``` @@ -1042,22 +1134,24 @@ Sends an extended command to the location subsystem. This API can only be called **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | command | LocationCommand | Yes| Extended command (string) to be sent.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the operation result.| -- Example +**Example** - ``` + ```js var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { - console.log('promise, sendCommand: ' + result); + console.log('promise, sendCommand: ' + JSON.stringify(result)); }); ``` @@ -1068,23 +1162,29 @@ isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&l Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Example +**Example** - ``` + ```js geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result); + if (err) { + console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); + } + if (result) { + console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); + } }); ``` @@ -1095,27 +1195,29 @@ isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean> Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Example +**Example** - ``` + ```js geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + result); + console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); }); ``` @@ -1126,24 +1228,30 @@ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result); + if (err) { + console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); + } + if (result) { + console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); + } }); ``` @@ -1154,32 +1262,540 @@ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolea Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Return value +**Return value** + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + result); + console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); + }); + ``` + + +## geolocation.getCountryCode9+ + +getCountryCode(callback: AsyncCallback<CountryCode>) : void; + +Query the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | + +**Example**: + + ```js + geolocation.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.getCountryCode9+ + +getCountryCode() : Promise<CountryCode>; + +Query the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<CountryCode> | return country code. | + +**Example**: + + ```js + geolocation.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + ``` + + +## geolocation.enableLocationMock9+ + +enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; + +Enable the position simulation function of a scene, and only one scene can be enabled at the same time. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.enableLocationMock(request, (err, result) => { + if (err) { + console.log('enableLocationMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('enableLocationMock: result=' + JSON.stringify(result)); + } + }); + ``` + +## geolocation.enableLocationMock9+ + +enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; + +Enable the position simulation function of a scene, and only one scene can be enabled at the same time. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | + + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.enableLocationMock(request) + .then((result) => { + if (result) { + console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.disableLocationMock9+ + +disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; + +To disable the position simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.disableLocationMock(request, (err, result) => { + if (err) { + console.log('disableLocationMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('disableLocationMock: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.disableLocationMock9+ + +disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; + +To disable the position simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.disableLocationMock(request) + .then((result) => { + if (result) { + console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.setMockedLocations9+ + +setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; + +Set the simulated location information, and then report the simulated location at the time interval carried in the interface. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + geolocation.setMockedLocations(config, (err, data) => { + if (err) { + console.log('setMockedLocations: err=' + JSON.stringify(err)); + } + if (data) { + console.log('setMockedLocations: data=' + JSON.stringify(data)); + } + }); + ``` + +## geolocation.setMockedLocations9+ + +setMockedLocations(config: LocationMockConfig) : Promise<void>; + +Set the simulated location information, and then report the simulated location at the time interval carried in the interface. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations":locations}; + geolocation.setMockedLocations(config) + .then((result) => { + if (result) { + console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); + } + }); + ``` + + + +## geolocation.enableReverseGeocodingMock9+ + +enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; + +Enable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.enableReverseGeocodingMock((err, data) => { + if (err) { + console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + if (data) { + console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); + } + }); + ``` + + +## geolocation.enableReverseGeocodingMock9+ + +enableReverseGeocodingMock() : Promise<void>; + +Enable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.enableReverseGeocodingMock() + .then((result) => { + if (result) { + console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.disableReverseGeocodingMock9+ + +disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; + +Disable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | + +**Example**: + + ```js + geolocation.disableReverseGeocodingMock((err, result) => { + if (err) { + console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.disableReverseGeocodingMock9+ + +disableReverseGeocodingMock() : Promise<void>; + +Disable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.disableReverseGeocodingMock() + .then((result) => { + if (result) { + console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.setReverseGeocodingMockInfo9+ + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; + +Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var mockInfos = [ + {"location": {"locale": "shanghai", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "shanghai", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "beijing", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "beijing", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "shenzhen", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "shenzhen", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "wuhan", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "wuhan", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "chengdu", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "chengdu", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { + if (err) { + console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); + } + if (data) { + console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); + } }); ``` +## geolocation.setReverseGeocodingMockInfo9+ + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; + +Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var mockInfos = [ + {"location": {"locale": "shanghai", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "shanghai", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "beijing", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "beijing", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "shenzhen", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "shenzhen", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "wuhan", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "wuhan", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "chengdu", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "chengdu", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geolocation.setReverseGeocodingMockInfo(mockInfos) + .then((result) => { + if (result) { + console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); + } + }); + ``` + ## LocationRequestPriority @@ -1225,13 +1841,15 @@ Enumerates error codes of the location service. | Name| Default Value| Description| | -------- | -------- | -------- | -| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time.| +| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| +| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | ## ReverseGeoCodeRequest @@ -1279,24 +1897,25 @@ Defines a geographic location. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName | string | No| Landmark of the location.| -| countryCode | string | No| Country code.| -| countryName | string | No| Country name.| -| administrativeArea | string | No| Administrative region name.| -| subAdministrativeArea | string | No| Sub-administrative region name.| -| locality | string | No| Locality information. | -| subLocality | string | No| Sub-locality information. | -| roadName | string | No| Road name.| -| subRoadName | string | No| Auxiliary road information.| -| premises | string | No| House information.| -| postalCode | string | No| Postal code.| -| phoneNumber | string | No| Phone number.| -| addressUrl | string | No| Website URL.| -| descriptions | Array<string> | No| Additional description.| -| descriptionsSize | number | No| Total number of additional descriptions.| +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| +| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | ## LocationRequest @@ -1434,13 +2053,68 @@ Defines a location. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| altitude | number | Yes| Location altitude, in meters.| -| accuracy | number | Yes| Location accuracy, in meters.| -| speed | number | Yes| Speed, in m/s.| -| timeStamp | number | Yes| Location timestamp in the UTC format.| -| direction | number | Yes| Direction information.| -| timeSinceBoot | number | Yes| Location timestamp since boot.| -| additions | Array<string> | No| Additional information.| -| additionSize | number | No| Number of additional descriptions.| +| latitude7+ | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude7+ | number | Yes| Location altitude, in meters.| +| accuracy7+ | number | Yes| Location accuracy, in meters.| +| speed7+ | number | Yes| Speed, in m/s.| +| timeStamp7+ | number | Yes| Location timestamp in the UTC format.| +| direction7+ | number | Yes| Direction information.| +| timeSinceBoot7+ | number | Yes| Location timestamp since boot.| +| additions7+ | Array<string> | No| Additional information.| +| additionSize7+ | number | No| Number of additional descriptions.| +| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | + + +## ReverseGeocodingMockInfo9+ + +The configuration information of the reverse geocoding simulation function includes a location information and a place name information. + +**System capability**:SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | +| geoAddress | GeoAddress | Yes | Represents a geographic location. | + + +## LocationMockConfig9+ + +The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | +| locations | Array<Location> | Yes | Represents an array of mocked locations. | + + +## CountryCode9+ + +The country code information structure contains the country code string and the source information of the country code. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| country | string | Yes | Represents the country code string. | +| type | CountryCodeType | Yes | Indicates the source of country code information. | + + +## CountryCodeType9+ + +Country code source type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | +| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | +| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | +| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index f1ef654168a4696ee3f0e54e361a5e81ac7dc6a9..9e0e0bf5160d01596d0c6e0969c3cc783712f45a 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,6 +1,8 @@ # Data Request ->![](public_sys-resources/icon-note.gif) **NOTE** +This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. + +>**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. > @@ -18,17 +20,17 @@ import http from '@ohos.net.http'; // Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. let httpRequest = http.createHttp(); -// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. -// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ +// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. +// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. + // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. "EXAMPLE_URL", { method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. - // You can add the header field based on service requirements. + // You can add header fields based on service requirements. header: { 'Content-Type': 'application/json' }, @@ -48,7 +50,7 @@ httpRequest.request( console.info('cookies:' + data.cookies); // 8+ } else { console.info('error:' + JSON.stringify(err)); - // Call the destroy() method to release resources after the call is complete. + // Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy(); } } @@ -79,7 +81,7 @@ let httpRequest = http.createHttp(); ## HttpRequest -Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. +HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. ### request @@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ----------------------- | -| url | string | Yes | URL for initiating an HTTP request.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------- | +| url | string | Yes | URL for initiating an HTTP request.| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | **Example** @@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------ | ---- | -------------------------------------------------- | -| url | string | Yes | URL for initiating an HTTP request. | +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| **Return value** -| Type | Description | -| :-------------------- | :-------------------------------- | +| Type | Description | +| :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| @@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **NOTE** -> -> This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. +>This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. **System capability**: SystemCapability.Communication.NetStack @@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **NOTE** -> >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques **System capability**: SystemCapability.Communication.NetStack -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | -| method | [RequestMethod](#requestmethod) | No | Request method. | +| Name | Type | Mandatory| Description | +| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| method | [RequestMethod](#requestmethod) | No | Request method. | | extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | -| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.| -| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | -| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | +| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | +| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | +| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | ## RequestMethod @@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | -| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | +| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | | RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | -| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | +| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | | MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | | MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| | MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | @@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request. | REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | | UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | | INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | -| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | +| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | | BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| | UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | | GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | @@ -433,6 +433,17 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| -| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:
- 200: common error
- 202: parameter error
- 300: I/O error| +| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | + +## Error Codes + +| Error Code| Description | +| ------ | ------------------------------------------------------------ | +| -1 | Incorrect parameters. | +| 3 | Incorrect URL format. | +| 4 | Built-in request function, protocol, or option not found during build. | +| 5 | Unable to resolve the proxy. | +| 6 | Unable to resolve the host. | +| 7 | Unable to connect to the proxy or host. | diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 3d2f6f3e9703e606847e92822c62aa20c2811e8f..91059df152841c2317196bcd8496be2412f2fd30 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -49,7 +49,9 @@ getMediaLibrary(): MediaLibrary Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. -> **Note**: This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. +> **NOTE** +> +> This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -99,7 +101,9 @@ media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); fetchFileResult.getAllObject((err, fileAssetList) => { if (fileAssetList != undefined) { - fileAssetList.forEach(getAllObjectInfo); + fileAssetList.forEach(function(getAllObjectInfo){ + console.info("getAllObjectInfo.displayName :" + getAllObjectInfo.displayName); + }); } }); } @@ -137,7 +141,7 @@ let imagesfetchOp = { selectionArgs: [imageType.toString()], }; media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(dir)); + console.info("getFileAssets successfully: image number is "+ fetchFileResult.getCount()); }).catch(function(err){ console.info("getFileAssets failed with error:"+ err); }); @@ -161,7 +165,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback **Example** ``` -mediaLibrary.on('imageChange', () => { +media.on('imageChange', () => { // image file had changed, do something }) ``` @@ -449,7 +453,9 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>) Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -485,7 +491,9 @@ storeMediaAsset(option: MediaAssetOption): Promise<string> Stores a media asset. This API uses a promise to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -524,7 +532,9 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -566,7 +576,9 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g Starts image preview. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **** component can be used to render and display local images and network images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -606,7 +618,9 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with dataability:// or online images whose URIs start with https://. It uses a promise to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **** component can be used to render and display local images and network images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -651,7 +665,9 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -666,7 +682,7 @@ Starts media selection. This API uses an asynchronous callback to return the lis ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { @@ -686,7 +702,9 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -706,7 +724,7 @@ Starts media selection. This API uses a promise to return the list of URIs that ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { @@ -745,7 +763,7 @@ Provides APIs for encapsulating file asset attributes. | width | number | Yes | No | Image width, in pixels. | | height | number | Yes | No | Image height, in pixels. | | orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).| -| duration8+ | number | Yes | No | Duration, in seconds. | +| duration8+ | number | Yes | No | Duration, in ms. | | albumId | number | Yes | No | ID of the album to which the file belongs. | | albumUri8+ | string | Yes | No | URI of the album to which the file belongs. | | albumName | string | Yes | No | Name of the album to which the file belongs. | @@ -771,6 +789,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -806,6 +825,7 @@ Checks whether this file asset is a directory. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -843,6 +863,7 @@ Commits the modification in this file asset to the database. This API uses an as ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -879,6 +900,7 @@ Commits the modification in this file asset to the database. This API uses a pro ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -899,9 +921,11 @@ open(mode: string, callback: AsyncCallback<number>): void Opens this file asset. This API uses an asynchronous callback to return the result. -Note: Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -919,7 +943,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw', (openError, fd) => { if(fd > 0){ asset.close(fd); @@ -936,9 +960,11 @@ open(mode: string): Promise<number> Opens this file asset. This API uses a promise to return the result. -Note: Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -946,7 +972,7 @@ Note: Currently, the write operations are mutually exclusive. After the write op | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------------------------------- | -| mode | string | Yes | Mode of opening the file, for example, **r** (read-only), **w** (write-only), and **rw** (read-write).| +| mode | string | Yes | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).| **Return value** @@ -961,7 +987,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw') .then((fd) => { console.info('File fd!' + fd); @@ -978,7 +1004,7 @@ close(fd: number, callback: AsyncCallback<void>): void Closes this file asset. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -993,6 +1019,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1002,13 +1029,19 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd, (closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1019,7 +1052,7 @@ close(fd: number): Promise<void> Closes this file asset. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **'r'**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **'w'**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1039,6 +1072,7 @@ Closes this file asset. This API uses a promise to return the result. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1048,14 +1082,20 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd).then((closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1080,6 +1120,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1116,6 +1157,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1123,6 +1165,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (err, pixelmap) => { @@ -1157,6 +1200,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1164,6 +1208,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size) @@ -1197,6 +1242,7 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1238,6 +1284,7 @@ Favorites or unfavorites this file asset. This API uses a promise to return the ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1275,6 +1322,7 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1314,6 +1362,7 @@ Checks whether this file asset is favorited. This API uses a promise to return t ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1354,6 +1403,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1398,6 +1448,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1435,6 +1486,7 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1448,7 +1500,7 @@ async function example() { function isTrashCallBack(err, isTrash) { if (isTrash == true) { console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK isTrash = ' + isTrash); - asset.trash(true, trashCallBack); + asset.trash(true, istrashCallBack); } else { console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessfull = ' + err); @@ -1479,6 +1531,7 @@ Checks whether this file asset is in the trash. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1518,6 +1571,8 @@ Obtains the total number of files in the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE; let getFileCountOneOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], @@ -1547,6 +1602,7 @@ Checks whether the cursor is in the last row of the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1584,6 +1640,7 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1614,6 +1671,7 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1622,12 +1680,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, value) => { + fetchFileResult.getFirstObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1650,6 +1708,7 @@ Obtains the first file asset in the result set. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1672,8 +1731,6 @@ async function example() { Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1686,6 +1743,7 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1694,12 +1752,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, value) => { + fetchFileResult.getNextObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1710,8 +1768,6 @@ async function example() { Obtains the next file asset in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Return value** @@ -1724,6 +1780,7 @@ Obtains the next file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1734,7 +1791,7 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); const fetchCount = fetchFileResult.getCount(); console.info('mediaLibraryTest : count:' + fetchCount); - fileAsset = await fetchFileResult.getNextObject(); + let fileAsset = await fetchFileResult.getNextObject(); } ``` @@ -1756,6 +1813,7 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1764,12 +1822,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, value) => { + fetchFileResult.getLastObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1792,6 +1850,7 @@ Obtains the last file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1823,6 +1882,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1831,12 +1891,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, value) => { + fetchFileResult.getPositionObject(0, (err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1847,8 +1907,6 @@ getPositionObject(index: number): Promise<FileAsset> Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1867,6 +1925,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1875,12 +1934,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1, (err, value) => { + fetchFileResult.getPositionObject(1, (err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1891,8 +1950,6 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1905,6 +1962,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1913,12 +1971,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getAllObject((err, value) => { + fetchFileResult.getAllObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1941,6 +1999,7 @@ Obtains all the file assets in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -2068,6 +2127,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack); @@ -2107,6 +2170,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ @@ -2120,8 +2187,9 @@ async function example() { ## PeerInfo8+ Describes information about a registered device. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore | Name | Type | Readable| Writable| Description | | ---------- | -------------------------- | ---- | ---- | ---------------- | @@ -2138,12 +2206,12 @@ Enumerates media types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value| Description| -| ----- | ------ | ---- | -| FILE | 1 | File.| -| IMAGE | 3 | Image.| -| VIDEO | 4 | Video.| -| AUDIO | 5 | Audio.| +| Name | Description| +| ----- | ---- | +| FILE | File.| +| IMAGE | Image.| +| VIDEO | Video.| +| AUDIO | Audio.| ## FileKey8+ @@ -2166,7 +2234,7 @@ Enumerates key file information. | TITLE | title | Title in the file. | | ARTIST | artist | Artist of the file. | | AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in seconds. | +| DURATION | duration | Duration, in ms. | | WIDTH | width | Image width, in pixels. | | HEIGHT | height | Image height, in pixels. | | ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| @@ -2179,30 +2247,31 @@ Enumerates directory types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value| Description | -| ------------- | ------ | ------------------ | -| DIR_CAMERA | 0 | Directory of camera files.| -| DIR_VIDEO | 1 | Directory of video files. | -| DIR_IMAGE | 2 | Directory of image files. | -| DIR_AUDIO | 3 | Directory of audio files. | -| DIR_DOCUMENTS | 4 | Directory of documents. | -| DIR_DOWNLOAD | 5 | Download directory. | +| Name | Description | +| ------------- | ------------------ | +| DIR_CAMERA | Directory of camera files.| +| DIR_VIDEO | Directory of video files. | +| DIR_IMAGE | Directory of image files. | +| DIR_AUDIO | Directory of audio files. | +| DIR_DOCUMENTS | Directory of documents. | +| DIR_DOWNLOAD | Download directory. | ## DeviceType8+ Enumerates device types. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore -| Name | Default Value| Description | -| ------------ | ------ | ---------- | -| TYPE_UNKNOWN | 0 | Unknown.| -| TYPE_LAPTOP | 1 | Laptop.| -| TYPE_PHONE | 2 | Phone. | -| TYPE_TABLET | 3 | Tablet. | -| TYPE_WATCH | 4 | Smart watch. | -| TYPE_CAR | 5 | Vehicle-mounted device. | -| TYPE_TV | 6 | TV. | +| Name | Description | +| ------------ | ---------- | +| TYPE_UNKNOWN | Unknown.| +| TYPE_LAPTOP | Laptop.| +| TYPE_PHONE | Phone. | +| TYPE_TABLET | Tablet. | +| TYPE_WATCH | Smart watch. | +| TYPE_CAR | Vehicle-mounted device. | +| TYPE_TV | TV. | ## MediaFetchOptions7+ @@ -2222,6 +2291,7 @@ Describes options for fetching media files. ## Size8+ Describes the image size. +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | -------- | @@ -2232,7 +2302,9 @@ Describes the image size. Implements the media asset option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2247,7 +2319,9 @@ Implements the media asset option. Describes media selection option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index e6f796d1a08c0bce209a84e2999dcbf4f3b6a78c..98d55f53e7f3c51f33fc9505fccf33df846c9ef6 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,6 +1,7 @@ # Obtaining Process Information -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -409,7 +410,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number  \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| +| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| | maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index c9b06ebe5b0421b42ad09db4632c8242c4894cc2..ac9435450c7e47d70deb11ed0a5b7249eea8f368 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -29,7 +29,7 @@ Navigates to a specified page in the application. **Example** - ```js +```js router.push({ url: 'pages/routerpage2', params: { @@ -39,7 +39,7 @@ router.push({ }, }, }); - ``` +``` ## router.push9+ push(options: RouterOptions, mode: RouterMode): void @@ -56,7 +56,7 @@ Navigates to a specified page in the application. **Example** - ```js +```js router.push({ url: 'pages/routerpage2/routerpage2', params: { @@ -66,11 +66,11 @@ router.push({ }, }, },router.RouterMode.Standard); - ``` +``` ## router.replace -replace(options: RouterOptions, mode?: RouterMode): void +replace(options: RouterOptions): void Replaces the current page with another one in the application and destroys the current page. @@ -83,14 +83,14 @@ Replaces the current page with another one in the application and destroys the c **Example** - ```js +```js router.replace({ url: 'pages/detail', params: { data1: 'message', }, }); - ``` +``` ## router.replace9+ @@ -108,14 +108,14 @@ Replaces the current page with another one in the application and destroys the c **Example** - ```js +```js router.replace({ url: 'pages/detail/detail', params: { data1: 'message', }, }, router.RouterMode.Standard); - ``` +``` ## router.back @@ -132,9 +132,9 @@ Returns to the previous page or a specified page. **Example** - ```js -router.back({uri:'pages/detail'}); - ``` +```js +router.back({url:'pages/detail'}); +``` ## router.clear @@ -146,9 +146,9 @@ Clears all historical pages in the stack and retains only the current page at th **Example** - ```js +```js router.clear(); - ``` +``` ## router.getLength @@ -164,10 +164,10 @@ Obtains the number of pages in the current stack. | string | Number of pages in the stack. The maximum value is **32**.| **Example** - ```js +```js var size = router.getLength(); console.log('pages stack size = ' + size); - ``` +``` ## router.getState @@ -242,9 +242,9 @@ Disables the display of a confirm dialog box before returning to the previous pa **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** - ```js +```js router.disableAlertBeforeBackPage(); - ``` +``` ## router.getParams @@ -270,7 +270,7 @@ router.getParams(); Describes the page routing options. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite | Name | Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -314,7 +314,7 @@ export default { // detail page export default { onInit() { - console.info('showData1:' + router.getParams().data1); + console.info('showData1:' + router.getParams()[data1]); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 251c1d59b610f4d01372186d0e40d0521cf62ca8..64d76026eeb3981fd589401d71f599fc2112f9dd 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,8 +1,5 @@ # Update -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 Update module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. There are two types of updates: SD card update and over the air (OTA) update. @@ -10,135 +7,180 @@ There are two types of updates: SD card update and over the air (OTA) update. - The SD card update depends on the update packages and SD cards. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + ## Modules to Import ```js import update from '@ohos.update' ``` -## Required Permissions - -None - -## update.getUpdater +## update.getOnlineUpdater -getUpdater(upgradeFile: string, updateType?: UpdateTypes): Updater +getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater -Obtains the **Updater** object for local update. +Obtains an **OnlineUpdater** object. **System capability**: SystemCapability.Update.UpdateService **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | ------------ | -| upgradeFile | string | Yes | Update file. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | ---- | ---- | +| upgradeInfo | [UpgradeInfo](#upgradeinfo) | Yes | **UpgradeInfo** object.| **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [Updater](#updater) | **OnlineUpdater** object.| **Example** ``` try { - let updater = update.getUpdater('/data/updater/updater.zip', 'OTA'); + var upgradeInfo = { + upgradeApp: "com.ohos.ota.updateclient", + businessType: { + vendor: update.BusinessVendor.PUBLIC, + subType: update.BusinessSubType.FIRMWARE + } + } + let updater = update.getOnlineUpdater(upgradeInfo); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get updater error: ${error}`); } ``` -## update.getUpdaterForOther +## update.getRestorer -getUpdaterForOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater +getRestorer(): Restorer -Obtains the **Updater** object for the device to be updated. +Obtains a **Restorer** object for restoring factory settings. **System capability**: SystemCapability.Update.UpdateService -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | --------------------- | -| upgradeFile | string | Yes | Update file. | -| device | string | Yes | Device to be updated. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [Restorer](#restorer) | **Restorer** object for restoring factory settings.| **Example** ``` try { - let updater = update.getUpdaterForOther('/data/updater/updater.zip', '1234567890', 'OTA'); + let restorer = update.getRestorer(); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get restorer: ${error}`); } ``` -## update.getUpdaterFromOther +## update.getLocalUpdater -getUpdaterFromOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater +getLocalUpdater(): LocalUpdater -Obtains the **Updater** object from another device for the device to be updated. +Obtains a **LocalUpdater** object. **System capability**: SystemCapability.Update.UpdateService -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | --------------------- | -| upgradeFile | string | Yes | Update file. | -| device | string | Yes | Device to be updated. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | - **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [LocalUpdater](#localupdater) | **LocalUpdater** object.| **Example** ``` try { - let updater = update.getUpdaterFromOther('/data/updater/updater.zip', '1234567890', 'OTA'); + let localUpdater = update.getLocalUpdater(); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get localUpdater error: ${error}`); } ``` ## Updater +### checkNewVersion + +checkNewVersion(callback: AsyncCallback\): void + +Checks whether a new version is available. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[CheckResult](#checkresult)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.checkNewVersion((err, result) => { + console.log(`checkNewVersion isExistNewVersion ${result?.isExistNewVersion}`); +}); +``` + +### checkNewVersion + +checkNewVersion(): Promise\ + +Checks whether a new version is available. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[CheckResult](#checkresult)> | Promise used to return the result.| + +**Example** + +``` +updater.checkNewVersion().then(result => { + console.log(`checkNewVersion isExistNewVersion: ${result.isExistNewVersion}`); + // Version digest information + console.log(`checkNewVersion versionDigestInfo: ${result.newVersionInfo.versionDigestInfo.versionDigest}`); +}).catch(err => { + console.log(`checkNewVersion promise error ${JSON.stringify(err)}`); +}); +``` + ### getNewVersionInfo getNewVersionInfo(callback: AsyncCallback\): void -Obtains the new version information. This function uses an asynchronous callback to return the result. +Obtains information about the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[NewVersionInfo](#newversioninfo)> | No | Callback used to return the new version information. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | Yes | Callback used to return the result.| **Example** ``` -updater.getNewVersionInfo(info => { - console.log("getNewVersionInfo success " + info.status); - console.log(`info versionName = ` + info.checkResult[0].versionName); - console.log(`info versionCode = ` + info.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); +updater.getNewVersionInfo((err, info) => { + console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info?.versionComponents[0].innerVersion}`); }); ``` @@ -146,451 +188,1562 @@ updater.getNewVersionInfo(info => { getNewVersionInfo(): Promise\ -Obtains the new version information. This function uses a promise to return the result. +Obtains information about the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the result.| **Example** ``` -updater.getNewVersionInfo().then(value => { - console.log(`info versionName = ` + value.checkResult[0].versionName); - console.log(`info versionCode = ` + value.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); +updater.getNewVersionInfo().then(info => { + console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info.versionComponents[0].innerVersion}`); }).catch(err => { - console.log("getNewVersionInfo promise error: " + err.code); + console.log(`getNewVersionInfo promise error ${JSON.stringify(err)}`); }); ``` -### checkNewVersion +### getNewVersionDescription -checkNewVersion(callback: AsyncCallback\): void +getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions, callback: AsyncCallback\>): void -Checks whether the current version is the latest. This function uses an asynchronous callback to return the result. +Obtains the description file of the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | No | Callback used to return the new version information. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| +| callback | AsyncCallback\>) | Yes | Callback used to return the result.| **Example** ``` -updater.checkNewVersion(info => { - console.log("checkNewVersion success " + info.status); - console.log(`info versionName = ` + info.checkResult[0].versionName); - console.log(`info versionCode = ` + info.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { + console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); + console.log(`getNewVersionDescription err ${JSON.stringify(err)}`); }); ``` -### checkNewVersion +### getNewVersionDescription + +getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions): Promise\>; + +Obtains the description file of the new version. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\> | Promise used to return the result.| + +**Example** -checkNewVersion(): Promise\ +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { + console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); +}).catch(err => { + console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`); +}); +``` + +### getCurrentVersionInfo + +getCurrentVersionInfo(callback: AsyncCallback\): void + +Obtains information about the current version. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** -Checks whether the current version is the latest. This function uses a promise to return the result. +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[CurrentVersionInfo](#currentversioninfo)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.getCurrentVersionInfo((err, info) => { + console.log(`info osVersion = ${info?.osVersion}`); + console.log(`info deviceName = ${info?.deviceName}`); + console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); +}); +``` + +### getCurrentVersionInfo + +getCurrentVersionInfo(): Promise\ + +Obtains information about the current version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise used to return the result.| **Example** ``` -updater.checkNewVersion().then(value => { - console.log(`info versionName = ` + value.checkResult[0].versionName); - console.log(`info versionCode = ` + value.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); +updater.getCurrentVersionInfo().then(info => { + console.log(`info osVersion = ${info.osVersion}`); + console.log(`info deviceName = ${info.deviceName}`); + console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); }).catch(err => { - console.log("checkNewVersion promise error: " + err.code); + console.log(`getCurrentVersionInfo promise error ${JSON.stringify(err)}`); }); ``` -### verifyUpdatePackage +### getCurrentVersionDescription -verifyUpdatePackage(upgradeFile: string, certsFile: string): void +getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: AsyncCallback\>): void -Verifies whether the update package is valid. +Obtains the description file of the current version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | --------- | ---------------------------------------- | -| upgradeFile | string | Yes | Path of the update package to be verified. | -| certsFile | string | Yes | Certificate path. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| +| callback | AsyncCallback\>) | Yes | Callback used to return the result.| **Example** ``` -updater.on("verifyProgress", callback => { - console.info('on verifyProgress ' + callback.percent); +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { + console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); + console.log(`getCurrentVersionDescription err ${JSON.stringify(err)}`); }); -update.verifyUpdatePackage("XXX", "XXX"); ``` -### rebootAndCleanUserData8+ +### getCurrentVersionDescription -rebootAndCleanUserData(): Promise\ +getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise\> -Reboots the device and clears the user partition data. This function uses a promise to return the result. +Obtains the description file of the current version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| + **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\> | Promise used to return the result.| **Example** ``` -updater.rebootAndCleanUserData().then(result => { - console.log("rebootAndCleanUserData " + result); +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getCurrentVersionDescription(descriptionOptions).then(info => { + console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); }).catch(err => { - console.info("rebootAndCleanUserData promise error: " + err.code); + console.log(`getCurrentVersionDescription promise error ${JSON.stringify(err)}`); }); ``` -### rebootAndCleanUserData8+ +### getTaskInfo -rebootAndCleanUserData(callback: AsyncCallback\): void +getTaskInfo(callback: AsyncCallback\): void -Reboots the device and clears the user partition data. This function uses a promise to return the result. +Obtains information about the update task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[TaskInfo](#taskinfo)> | Yes | Callback used to return the result.| **Example** ``` -updater.rebootAndCleanUserData(result => { - console.log("rebootAndCleanUserData ", result) +updater.getTaskInfo((err, info) => { + console.log(`getTaskInfo isexistTask= ${info?.existTask}`); }); ``` -### applyNewVersion +### getTaskInfo -applyNewVersion(): Promise\ +getTaskInfo(): Promise\ -Installs the update package. This function uses a promise to return the result. +Obtains information about the update task. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[TaskInfo](#taskinfo)> | Promise used to return the result.| **Example** ``` -updater.applyNewVersion().then(result => { - console.log("appVewVersion ", result) +updater.getTaskInfo().then(info => { + console.log(`getTaskInfo isexistTask= ${info.existTask}`); }).catch(err => { - console.info("applyNewVersion promise error: " + err.code); + console.log(`getTaskInfo promise error ${JSON.stringify(err)}`); }); ``` -### applyNewVersion +### download -applyNewVersion(callback: AsyncCallback\): void +download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions, callback: AsyncCallback\): void -Installs the update package. This function uses a promise to return the result. +Downloads the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -updater.applyNewVersion(result => { - console.log("applyNewVersion ", result) +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Download options +var downloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network + order: update.Order.DOWNLOAD // Download +} +updater.download(versionDigestInfo, downloadOptions, (err) => { + console.log(`download error ${JSON.stringify(err)}`); }); ``` ### download -download(): void +download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions): Promise\ -Downloads the new version and displays the download process. +Downloads the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + **Example** ``` -updater.on("downloadProgress", progress => { - console.log("downloadProgress on" + progress); - console.log(`downloadProgress status: ` + progress.status); - console.log(`downloadProgress percent: ` + progress.percent); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Download options +var downloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network + order: update.Order.DOWNLOAD // Download +} +updater.download(versionDigestInfo, downloadOptions).then(() => { + console.log(`download start`); +}).catch(err => { + console.log(`download error ${JSON.stringify(err)}`); }); -updater.download(); ``` -### upgrade +### resumeDownload + +resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: ResumeDownloadOptions, callback: AsyncCallback\): void + +Resumes download of the new version. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for resuming download +var resumeDownloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network +} +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { + console.log(`resumeDownload error ${JSON.stringify(err)}`); +}); +``` -upgrade():void +### resumeDownload -Starts an update. +resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: ResumeDownloadOptions): Promise\ + +Resumes download of the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + **Example** ``` -updater.on("upgradeProgress", progress => { - console.log("upgradeProgress on" + progress); - console.log(`upgradeProgress status: ` + progress.status); - console.log(`upgradeProgress percent: ` + progress.percent); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for resuming download +var resumeDownloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network +} +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { + console.log(`resumeDownload start`); +}).catch(err => { + console.log(`resumeDownload error ${JSON.stringify(err)}`); }); -updater.upgrade(); ``` -### setUpdatePolicy +### pauseDownload -setUpdatePolicy(policy: UpdatePolicy, callback: AsyncCallback\): void +pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseDownloadOptions, callback: AsyncCallback\): void -Sets the update policy. This function uses an asynchronous callback to return the result. +Pauses download of the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| policy | [UpdatePolicy](#updatepolicy) | Yes | Update policy to set. | -| callback | Callback used to return the execution result. | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -// Set the update policy. -let policy = { - autoDownload: false, - autoDownloadNet: true, - mode: 2, - autoUpgradeInterval: [ 2, 3 ], - autoUpgradeCondition: 2 +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for pausing download +var pauseDownloadOptions = { + isAllowAutoResume: true // Whether to allow automatic resuming of download } -updater.setUpdatePolicy(policy, result => { - console.log("setUpdatePolicy ", result) +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { + console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` -### setUpdatePolicy +### pauseDownload -setUpdatePolicy(policy: UpdatePolicy): Promise\ +pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseDownloadOptions): Promise\ -Sets the update policy. This function uses a promise to return the result. +Resumes download of the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------------- | --------- | --------------------- | -| policy | [UpdatePolicy](#updatepolicy) | Yes | Update policy to set. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download.| **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| **Example** ``` -let policy = { - autoDownload: false, - autoDownloadNet: true, - mode: 2, - autoUpgradeInterval: [ 2, 3 ], - autoUpgradeCondition: 2 +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for pausing download +var pauseDownloadOptions = { + isAllowAutoResume: true // Whether to allow automatic resuming of download } -updater.setUpdatePolicy(policy).then(result => - console.log("setUpdatePolicy ", result) -).catch(err => { - console.log("setUpdatePolicy promise error: " + err.code); +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { + console.log(`pauseDownload`); +}).catch(err => { + console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` -### getUpdatePolicy +### upgrade -getUpdatePolicy(callback: AsyncCallback\): void +upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, callback: AsyncCallback\): void -Obtains the update policy. This function uses an asynchronous callback to return the result. +Updates the version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\<[UpdatePolicy](#updatepolicy)> | No | Callback used to return the update policy. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -updater.getUpdatePolicy(policy => { - console.log("getUpdatePolicy success"); - console.log(`policy autoDownload = ` + policy.autoDownload); - console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); - console.log(`policy mode = ` + policy.mode); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Installation options +var upgradeOptions = { + order: update.Order.INSTALL // Installation command +} +updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { + console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` -### getUpdatePolicy +### upgrade -getUpdatePolicy(): Promise\ +upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): Promise\ -Obtains the update policy. This function uses a promise to return the result. +Updates the version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options.| + **Return value** -| Type | Description | -| --------------------------------------- | ---------------------------------------- | -| Promise\<[UpdatePolicy](#updatepolicy)> | Promise used to return the update policy. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| **Example** ``` -updater.getUpdatePolicy().then(value => { - console.log(`info autoDownload = ` + value.autoDownload); - console.log(`info autoDownloadNet = ` + value.autoDownloadNet); - console.log(`info mode = ` + value.mode); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Installation options +var upgradeOptions = { + order: update.Order.INSTALL // Installation command +} +updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { + console.log(`upgrade start`); }).catch(err => { - console.log("getUpdatePolicy promise error: " + err.code); + console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` -## UpdateTypes +### clearError + +clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, callback: AsyncCallback\): void -Enumerates update types. +Clears errors. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Description | -| ----- | ------------- | -| OTA | OTA update. | -| patch | Patch update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| clearOptions | [ClearOptions](#clearoptions) | Yes | Clear options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for clearing errors +var clearOptions = { + status: update.UpgradeStatus.UPGRADE_FAIL, +} +updater.clearError(versionDigestInfo, clearOptions, (err) => { + console.log(`clearError error ${JSON.stringify(err)}`); +}); +``` -## PackageTypes +### clearError -Enumerates update package types. +clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Promise\ + +Clears errors. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| -------------------- | ------------- | --------------------------------------- | -| PACKAGE_TYPE_NORMAL | 1 | Common update package. | -| PACKAGE_TYPE_BASE | 2 | Basic update package. | -| PACKAGE_TYPE_CUST | 3 | Custom update package. | -| PACKAGE_TYPE_PRELOAD | 4 | Preinstalled update package. | -| PACKAGE_TYPE_COTA | 5 | Parameter configuration update package. | -| PACKAGE_TYPE_VERSION | 6 | Version update package. | -| PACKAGE_TYPE_PATCH | 7 | Patch package. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| clearOptions | [ClearOptions](#clearoptions) | Yes | Update options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for clearing errors +var clearOptions = { + status: update.UpgradeStatus.UPGRADE_FAIL, +} +updater.clearError(versionDigestInfo, clearOptions).then(() => { + console.log(`clearError success`); +}).catch(err => { + console.log(`clearError error ${JSON.stringify(err)}`); +}); +``` + +### getUpgradePolicy -## InstallMode +getUpgradePolicy(callback: AsyncCallback\): void -Enumerates update modes. +Obtains the update policy. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| ------------------- | ------------- | ----------------- | -| INSTALL_MODE_NORMAL | 0 | Normal update. | -| INSTALL_MODE_NIGHT | 1 | Update at night. | -| INSTALL_MODE_AUTO | 2 | Automatic update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.getUpgradePolicy((err, policy) => { + console.log(`policy downloadStrategy = ${policy?.downloadStrategy}`); + console.log(`policy autoUpgradeStrategy = ${policy?.autoUpgradeStrategy}`); +}); +``` + +### getUpgradePolicy -## NewVersionStatus +getUpgradePolicy(): Promise\ -Enumerates new version check results. +Obtains the update policy. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| ------------------- | ------------- | ---------------------------------------- | -| VERSION_STATUS_ERR | -1 | System error while checking for the new version. | -| VERSION_STATUS_NEW | 0 | New version detected. | -| VERSION_STATUS_NONE | 1 | No new version detected. | -| VERSION_STATUS_BUSY | 2 | System busy while checking for the new version. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise\<[UpgradePolicy](#upgradepolicy)> | Promise used to return the result.| + +**Example** + +``` +updater.getUpgradePolicy().then(policy => { + console.log(`policy downloadStrategy = ${policy.downloadStrategy}`); + console.log(`policy autoUpgradeStrategy = ${policy.autoUpgradeStrategy}`); +}).catch(err => { + console.log(`getUpgradePolicy promise error ${JSON.stringify(err)}`); +}); +``` -## UpdatePolicy +### setUpgradePolicy -Defines the update policy. +setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\): void + +Sets the update policy. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------------- | --------------------------- | --------- | ------------------------------------ | -| autoDownload | bool | Yes | Automatic update switch. | -| installMode | [InstallMode](#installmode) | Yes | Update mode. | -| autoUpgradeInterval | Array\ | Yes | Period of time for automatic update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## NewVersionInfo +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------- | +| policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -Defines the new version information. +**Example** + +``` +let policy = { + downloadStrategy: false, + autoUpgradeStrategy: false, + autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes +} +updater.setUpgradePolicy(policy, (err) => { + console.log(`setUpgradePolicy result: ${err}`); +}); +``` + +### setUpgradePolicy + +setUpgradePolicy(policy: UpgradePolicy): Promise\ + +Sets the update policy. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| --------------- | ---------------------------------------- | --------- | -------------------------------- | -| status | [NewVersionStatus](#newversionstatus) | Yes | Update status. | -| errMsg | string | Yes | Error message. | -| checkResults | Array<[CheckResult](#checkresult)> | Yes | Version check result. | -| descriptionInfo | Array\<[DescriptionInfo](#descriptioninfo)> | Yes | Version description information. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## CheckResult +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------------- | ---- | ------ | +| policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy.| + +**Return value** + +| Type | Description | +| ---------------- | --------------- | +| Promise\ | Promise used to return the result.| -Defines the version check result. +**Example** + +``` +let policy = { + downloadStrategy: false, + autoUpgradeStrategy: false, + autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes +} +updater.setUpgradePolicy(policy).then(() => { + console.log(`setUpgradePolicy success`); +}).catch(err => { + console.log(`setUpgradePolicy promise error ${JSON.stringify(err)}`); +}); +``` + +### terminateUpgrade + +terminateUpgrade(callback: AsyncCallback\): void + +Terminates the update. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------- | ----------------------------- | --------- | --------------------------------- | -| versionName | string | Yes | Version name. | -| versionCode | number | Yes | Version code. | -| size | number | Yes | Version size. | -| verifyInfo | string | Yes | Version verification information. | -| packageType | [PackageTypes](#packagetypes) | Yes | Version type. | -| descriptionId | string | Yes | Version description information. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## DescriptionInfo +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +updater.terminateUpgrade((err) => { + console.log(`terminateUpgrade error ${JSON.stringify(err)}`); +}); +``` + +### terminateUpgrade + +terminateUpgrade(): Promise\ + +Terminates the update. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +updater.terminateUpgrade().then(() => { + console.log(`terminateUpgrade success`); +}).catch(err => { + console.log(`terminateUpgrade error ${JSON.stringify(err)}`); +}); +``` + + +### on +on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): void + +Enables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +updater.on(eventClassifyInfo, (eventInfo) => { + console.log("updater on " + JSON.stringify(eventInfo)); +}); +``` + +### off +off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): void + +Disables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +updater.off(eventClassifyInfo, (eventInfo) => { + console.log("updater off " + JSON.stringify(eventInfo)); +}); +``` + +## Restorer + +### factoryReset + +factoryReset(callback: AsyncCallback\): void + +Restores factory settings. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.FACTORY_RESET (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +restorer.factoryReset((err) => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +### factoryReset + +factoryReset(): Promise\ + +Restores factory settings. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.FACTORY_RESET (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +restorer.factoryReset().then(() => { + console.log(`factoryReset success`); +}).catch(err => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +## LocalUpdater + +### verifyUpgradePackage + +verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: AsyncCallback\): void + +Verifies the update package. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | [UpgradeFile](#upgradefile) | Yes | Update file.| +| certsFile | string | Yes | Path of the certificate file.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +``` +var upgradeFile = { + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +} + +localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +### verifyUpgradePackage + +verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\ + +Verifies the update package. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | [UpgradeFile](#upgradefile) | Yes | Update file.| +| certsFile | string | Yes | Path of the certificate file.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +var upgradeFile = { + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +} +localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { + console.log(`verifyUpgradePackage success`); +}).catch(err => { + console.log(`verifyUpgradePackage error ${JSON.stringify(err)}`); +}); +``` + +### applyNewVersion +applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>, callback: AsyncCallback\): void + +Installs the update package. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | Array<[UpgradeFile](#upgradefile)> | Yes | Update file.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +var upgradeFiles = [{ + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +}] + +localUpdater.applyNewVersion(upgradeFiles, (err) => { + console.log(`applyNewVersion error ${JSON.stringify(err)}`); +}); +``` + +### applyNewVersion + +applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\ + +Installs the update package. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +var upgradeFiles = [{ + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +}] +localUpdater.applyNewVersion(upgradeFiles).then(() => { + console.log(`applyNewVersion success`); +}).catch(err => { + console.log(`applyNewVersion error ${JSON.stringify(err)}`); +}); +``` + +### on +on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): void + +Enables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +function onTaskUpdate(eventInfo) { + console.log(`on eventInfo id `, eventInfo.eventId); +} + +localUpdater.on(eventClassifyInfo, onTaskUpdate); +``` + +### off +off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): void + +Disables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +function onTaskUpdate(eventInfo) { + console.log(`on eventInfo id `, eventInfo.eventId); +} + +localUpdater.off(eventClassifyInfo, onTaskUpdate); +``` + +## UpgradeInfo + +Represents update information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| upgradeApp | string | Yes | Application package name. | +| businessType | [BusinessType](#businesstype) | Yes | Update service type. | + +## BusinessType + +Enumerates update service types. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| vendor | [BusinessVendor](#businessvendor) | Yes | Application vendor. | +| subType | [BusinessSubType](#businesssubtype) | Yes | Update service sub-type. | + +## CheckResult + +Represents the package check result. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| isExistNewVersion | bool | Yes | Whether a new version is available. | +| newVersionInfo | [NewVersionInfo](#newversioninfo) | No | Information about the new version. | + +## NewVersionInfo + +Represents information about the new version. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | +| versionComponents | Array\<[VersionComponent](#versioncomponent)> | Yes | Version components. | + +## VersionDigestInfo + +Represents version digest information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigest | string | Yes | Version digest information. | + +## VersionComponent + +Represents a version component. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| componentId | number | Yes | Component ID. | +| componentType | [ComponentType](#componentyype) | Yes | Component type. | +| upgradeAction | [UpgradeAction](#upgradeaction) | Yes | Update mode. | +| displayVersion | string | Yes | Display version number. | +| innerVersion | string | Yes | Internal version number. | +| size | number | Yes | Update package size. | +| effectiveMode | [EffectiveMode](#effectivemode) | Yes | Effective mode. | +| descriptionInfo | [DescriptionInfo](#descriptioninfo) | Yes | Information about the version description file. | + +## DescriptionOptions + +Represents options of the description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| format | [DescriptionFormat](#descriptionformat) | Yes | Format of the description file. | +| language | string | Yes | Language of the description file. | + +## ComponentDescription + +Represents a component description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| componentId | string | Yes | Component ID. | +| descriptionInfo | [DescriptionInfo](#descriptioninfo) | Yes | Information about the description file. | + +## DescriptionInfo + +Represents information about the version description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| descriptionType | [DescriptionType](#descriptiontype) | Yes | Type of the description file. | +| content | string | Yes | Content of the description file. | + +## CurrentVersionInfo + +Represents information about the current version. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| osVersion | string | Yes | System version number. | +| deviceName | string | Yes | Device name. | +| versionComponents | Array\<[VersionComponent](#vesioncomponent)> | No | Version components. | + +## DownloadOptions + +Represents download options. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| allowNetwork | [NetType](#nettype) | Yes | Network type. | +| order | [Order](#order) | Yes | Update command. | + +## ResumeDownloadOptions + +Represents options for resuming download. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| allowNetwork | [NetType](#nettype) | Yes | Network type. | + +## PauseDownloadOptions + +Represents options for pausing download. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| isAllowAutoResume | bool | Yes | Whether to allow automatic resuming of download. | + +## UpgradeOptions + +Represents update options. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| order | [Order](#order) | Yes | Update command. | + +## ClearOptions + +Represents options for clearing errors. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| status | [UpgradeStatus](#upgradestatus) | Yes | Error status. | + +## UpgradePolicy + +Represents an update policy. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| downloadStrategy | bool | Yes | Automatic download policy. | +| autoUpgradeStrategy | bool | Yes | Automatic update policy. | +| autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | Yes | Automatic update period.| + +## UpgradePeriod + +Represents a period for automatic update. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| start | number | Yes | Start time. | +| end | number | Yes | End time. | + +## TaskInfo + +Represents task information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| existTask | bool | Yes | Whether a task exists. | +| taskBody | [TaskBody](#taskinfo) | Yes | Task data. | + +## EventInfo + +Represents event information. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| eventId | [EventId](#eventid) | Yes | Event ID. | +| taskBody | [TaskBody](#taskinfo) | Yes | Task data. | + +## TaskBody + +Represents task data. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | +| status | [UpgradeStatus](#upgradestatus) | Yes | Update status. | +| subStatus | number | No | Sub-status. | +| progress | number | Yes | Progress. | +| installMode | number | Yes | Installation mode. | +| errorMessages | Array\<[ErrorMessage](#errormessage)> | No | Error message. | +| versionComponents | Array\<[VersionComponent](#versioncomponent)> | Yes | Version components. | + +## ErrorMessage + +Represents an error message. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| errorCode | number | Yes | Error code. | +| errorMessage | string | Yes | Error description. | + +## EventClassifyInfo + +Represents event type information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| eventClassify | [EventClassify](#eventclassify) | Yes | Event type. | +| extraInfo | string | Yes | Additional information. | + +## UpgradeFile + +Represents an update file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| fileType | [ComponentType](#componenttype) | Yes | File type. | +| filePath | string | Yes | File path. | + +## UpgradeTaskCallback + +### (eventInfo: [EventInfo](#eventinfo)): void + +Event callback. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| --------------- | ---------------------------------------- | ---- | ---- | +| eventInfo | [EventInfo](#eventinfo) | Yes | Event information.| + +## BusinessVendor + +Device vendor. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| PUBLIC | "public" | Open source. | + +## BusinessSubType + +Represents an update type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| FIRMWARE | 1 | Firmware. | + +## ComponentType + +Represents a component type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| OTA | 1 | Firmware. | + +## UpgradeAction + +Represents an update mode. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| UPGRADE | "upgrade" | Differential package. | +| RECOVERY | "recovery" | Recovery package. | + +## EffectiveMode + +Represents an effective mode. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| COLD | 1 | Cold update. | +| LIVE | 2 | Live update. | +| LIVE_AND_COLD | 3 | Hybrid live and cold update. | + +## DescriptionType + +Represents a description file type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| CONTENT | 0 | Content. | +| URI | 1 | Link. | + +## DescriptionFormat + +Represents a description file format. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| STANDARD | 0 | Standard format. | +| SIMPLIFIED | 1 | Simple format. | + +## NetType + +Enumerates network types. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| CELLULAR | 1 | Data network. | +| METERED_WIFI | 2 | Wi-Fi hotspot. | +| NOT_METERED_WIFI | 4 | Non Wi-Fi hotspot. | +| WIFI | 6 | WIFI | +| CELLULAR_AND_WIFI | 7 | Data network and Wi-Fi. | + +## Order + +Represents an update command. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| DOWNLOAD | 1 | Download. | +| INSTALL | 2 | Install. | +| DOWNLOAD_AND_INSTALL | 3 | Download and install. | +| APPLY | 4 | Apply. | +| INSTALL_AND_APPLY | 6 | Install and apply. | + +## UpgradeStatus + +Enumerates update states. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| WAITING_DOWNLOAD | 20 | Waiting for download. | +| DOWNLOADING | 21 | Downloading. | +| DOWNLOAD_PAUSED | 22 | Download paused. | +| DOWNLOAD_FAIL | 23 | Download failed. | +| WAITING_INSTALL | 30 | Waiting for installation. | +| UPDATING | 31 | Updating. | +| WAITING_APPLY | 40 | Waiting for applying the update. | +| APPLYING | 21 | Applying the update. | +| UPGRADE_SUCCESS | 50 | Update succeeded. | +| UPGRADE_FAIL | 51 | Update failed. | + +## EventClassify + +Represents an event type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| TASK | 0x01000000 | Task event. | + +## EventId -Defines the version description information. +Enumerates event IDs. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------- | ------ | --------- | ------------------------------ | -| descriptionId | string | Yes | Version ID information. | -| content | string | Yes | Version changelog information. | +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| EVENT_TASK_BASE | 0x01000000 | Indicates a task event. | +| EVENT_TASK_RECEIVE | 0x01000001 | Indicates that a task is received. | +| EVENT_TASK_CANCEL | 0x01000010 | Indicates that a task is cancelled. | +| EVENT_DOWNLOAD_WAIT | 0x01000011 | Indicates the state of waiting for the download. | +| EVENT_DOWNLOAD_START | 0x01000100 | Indicates that the download starts. | +| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Indicates the download progress update. | +| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Indicates that the download is paused. | +| EVENT_DOWNLOAD_RESUME | 0x01000111 | Indicates that the download is resumed. | +| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Indicates that the download succeeded. | +| EVENT_DOWNLOAD_FAIL | 0x01001001 | Indicates that the download failed. | +| EVENT_UPGRADE_WAIT | 0x01001010 | Indicates the state of waiting for the update. | +| EVENT_UPGRADE_START | 0x01001011 | Indicates that the update starts. | +| EVENT_UPGRADE_UPDATE | 0x01001100 | Indicates that the update is in progress. | +| EVENT_APPLY_WAIT | 0x01001101 | Indicates the state of waiting for applying the update. | +| EVENT_APPLY_START | 0x01001110 | Indicates the state of applying the update. | +| EVENT_UPGRADE_SUCCESS | 0x01001111 | Indicates that the update succeeded. | +| EVENT_UPGRADE_FAIL | 0x01010000 | Indicates that the update failed. | diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 2871e53f5e753bf52109e2d9c2e95b2c1d4c8808..55694ec1cb024a25affa93feca40b2a73ef38234 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -1,6 +1,7 @@ # URL String Parsing -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -25,7 +26,7 @@ Creates a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object | +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| **Example** @@ -48,10 +49,10 @@ Appends a key-value pair into the query string. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the key-value pair to append. | - | value | string | Yes | Value of the key-value pair to append. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the key-value pair to append.| +| value | string | Yes| Value of the key-value pair to append.| **Example** @@ -72,9 +73,9 @@ Deletes key-value pairs of the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the key-value pairs to delete. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the key-value pairs to delete.| **Example** @@ -95,15 +96,15 @@ Obtains all the key-value pairs based on the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to obtain all key-value pairs. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to obtain all key-value pairs.| **Return value** - | Type | Description | - | -------- | -------- | - | string[] | All key-value pairs matching the specified key. | +| Type| Description| +| -------- | -------- | +| string[] | All key-value pairs matching the specified key.| **Example** @@ -125,9 +126,9 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<[string, string]> | ES6 iterator. | +| Type| Description| +| -------- | -------- | +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -149,18 +150,18 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callbackfn | function | Yes | Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance. | - | thisArg | Object | No | Value to use when the callback is invoked. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value to use when the callback is invoked.| **Table 1** callbackfn parameter description - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | value | string | Yes | Value that is currently traversed. | - | key | string | Yes | Key that is currently traversed. | - | searchParams | Object | Yes | Instance that invokes the **forEach** method. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string | Yes| Value that is currently traversed.| +| key | string | Yes| Key that is currently traversed.| +| searchParams | Object | Yes| Instance that invokes the **forEach** method.| **Example** @@ -182,16 +183,16 @@ Obtains the value of the first key-value pair based on the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to obtain the value. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to obtain the value.| **Return value** - | Type | Description | - | -------- | -------- | - | string | Returns the value of the first key-value pair if obtained. | - | null | Returns null if no value is obtained. | +| Type| Description| +| -------- | -------- | +| string | Returns the value of the first key-value pair if obtained.| +| null | Returns null if no value is obtained.| **Example** @@ -212,15 +213,15 @@ Checks whether a key has a value. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to search for its value. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to search for its value.| **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the value exists; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the value exists; returns **false** otherwise.| **Example** @@ -241,10 +242,10 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the value to set. | - | value | string | Yes | Value to set. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the value to set.| +| value | string | Yes| Value to set.| **Example** @@ -282,9 +283,9 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<string> | ES6 iterator that contains the keys of all the key-value pairs. | +| Type| Description| +| -------- | -------- | +| IterableIterator<string> | ES6 iterator that contains the keys of all the key-value pairs.| **Example** @@ -306,9 +307,9 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<string> | ES6 iterator that contains the values of all the key-value pairs. | +| Type| Description| +| -------- | -------- | +| IterableIterator<string> | ES6 iterator that contains the values of all the key-value pairs.| **Example** @@ -330,9 +331,9 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<[string, string]> | ES6 iterator. | +| Type| Description| +| -------- | -------- | +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -354,9 +355,9 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Return value** - | Type | Description | - | -------- | -------- | - | string | String of serialized search parameters, which is percent-encoded if necessary. | +| Type| Description| +| -------- | -------- | +| string | String of serialized search parameters, which is percent-encoded if necessary.| **Example** @@ -400,10 +401,10 @@ Creates a URL. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | url | string | Yes | Input object. | - | base | string \ | URL | No | Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| **Example** @@ -433,9 +434,9 @@ Converts the parsed URL into a string. **Return value** - | Type | Description | - | -------- | -------- | - | string | Website address in a serialized string. | +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| **Example** @@ -455,12 +456,12 @@ Converts the parsed URL into a JSON string. **Return value** - | Type | Description | - | -------- | -------- | - | string | Website address in a serialized string. | +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| **Example** ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON() -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 83ed07f3f720da23ff5c006938d15bd2ea660751..71b0490ea8c610dc0169222042ec7770c19d0a83 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,6 +1,9 @@ # USB -> **NOTE**
+This module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. + +> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index a4ae0d235f5e2ff3297c2bddb887890967213a29..afa1c20bcd4eace98512772fb3cd7160d23a5b92 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -61,7 +61,7 @@ Obtains detailed information about a system error code. **Example** ```js - var errnum = 10; // 10 is the system error code. + var errnum = 10; // 10 is a system error code. var result = util.getErrorString(errnum); console.log("result = " + result); ``` @@ -104,14 +104,16 @@ Calls back an asynchronous function. In the callback, the first parameter indica promiseWrapper(original: (err: Object, value: Object) => void): Object -> **Introduce**
-> Deprecated starting from API version 9, it is recommended to use [util.promisify9 +] (\utilpromisify9) instead. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. Processes an asynchronous function and returns a promise version. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | original | Function | Yes| Asynchronous function.| @@ -136,7 +138,7 @@ Processes an asynchronous function and returns a promise version. promisify(original: (err: Object, value: Object) => void): Function -Processes an asynchronous function and returns a promise function. +Processes an asynchronous function and returns a promise. **System capability**: SystemCapability.Utils.Lang @@ -148,7 +150,7 @@ Processes an asynchronous function and returns a promise function. **Return value** | Type| Description| | -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise version.| +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| **Example** ```js @@ -165,7 +167,6 @@ Processes an asynchronous function and returns a promise function. }) ``` - ## TextDecoder ### Attributes @@ -217,7 +218,7 @@ Decodes the input content. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | Unit8Array | Yes| Uint8Array to decode.| +| input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| **Table 2** options @@ -982,7 +983,6 @@ Performs subsequent operations after a value is removed. **Example** ```js var arr = []; - var arr = []; class ChildLruBuffer extends util.LruBuffer { constructor() diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index e89a471130d3fc8d50350fd33bee3bfbcaf8b6ef..21e43edc10b5e4fd5acf567ceabb822f26935ade 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -1,6 +1,7 @@ # XML Parsing and Generation -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md index 42ac10339280af072effe49c7850c0a5fc1087d3..5f7d75d5406fd705e5a0716ff9d94fd3dd73de22 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -1,13 +1,12 @@ # Button +The **\