diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 2f6b6ab2d850444294bb8a274ed76b06409d9ebb..0730fd77fd56fef492927c964e97ff47bc733610 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -2,6 +2,6 @@ - [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md) - [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md) -- [APIs](apis/apis.md) +- [APIs](apis/Readme-EN.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 591571711b2440ed4aba0f29e4bee2652dd6a114..b283ed84102e9e4dc2ce877ad6f7c425941dbead 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,17 +1,52 @@ # APIs -- [Console Logs](console-logs.md) -- [HiAppEvent](hiappevent.md) -- [Page Routing](page-routing.md) -- [Pop-up Window](pop-up-window.md) -- [Timer](timer.md) -- [Audio Management](js-apis-audio.md) -- [Audio Playback](audio-playback.md) -- [Device Information](device-information.md) -- [System Attribute](system-attribute.md) -- [Battery and Charging](battery-and-charging.md) -- [Screen Brightness](screen-brightness.md) -- [Globalization](globalization.md) -- [Resource Management](resource-management.md) -- [Updater](updater.md) +- Resource Management + - [Resource Manager](js-apis-resource-manager.md) + - [Internationalization \(intl\) ](js-apis-intl.md) + - [Internationalization \(i18n\) ](js-apis-i18n.md) +- Media + - [Audio Management](js-apis-audio.md) + - [Media Playback and Recording](js-apis-media.md) +- Data Management + - [File Management](js-apis-fileio.md) + - [Lightweight Storage](js-apis-data-storage.md) + - [Distributed Data Management](js-apis-distributed-data.md) + - [Relational Database](js-apis-data-rdb.md) + - [Result Set](js-apis-data-resultset.md) + - [DataAbilityPredicates](js-apis-data-ability.md) +- Account Management + - [Distributed Account Management](js-apis-distributed-account.md) +- Telephony Service + - [Call](js-apis-call.md) + - [SMS](js-apis-sms.md) + - [SIM Management](js-apis-sim.md) + - [Radio](js-apis-radio.md) +- Device Management + - [Sensors](js-apis-sensor.md) + - [Vibration](js-apis-vibrator.md) + - [Brightness](js-apis-brightness.md) + - [Battery Info](js-apis-battery-info.md) + - [Power Management](js-apis-power.md) + - [Running Lock](js-apis-runninglock.md) + - [Device Info](js-apis-device-info.md) + - [systemParameter](js-apis-system-parameter.md) + - [Device Management](js-apis-device-manager.md) + - [Window](js-apis-window.md) + - [Display](js-apis-display.md) +- Basic Features + - [Application Context](js-apis-basic-features-app-context.md) + - [Console Logs](js-apis-basic-features-logs.md) + - [Page Routing](js-apis-basic-features-routes.md) + - [Pop-up Window](js-apis-basic-features-pop-up.md) + - [Application Configuration](js-apis-basic-features-configuration.md) + - [Timer](js-apis-basic-features-timer.md) + - [Setting the System Time](js-apis-system-time.md) + - [Animation](js-apis-basic-features-animator.md) + - [HiAppEvent](js-apis-hiappevent.md) + - [Performance Tracing](js-apis-bytrace.md) +- Language Base Class Library + - [Obtaining Process Information](js-apis-process.md) + - [URL String Parsing](js-apis-url.md) + - [String Encoding and Decoding](js-apis-util.md) + - [Worker Startup](js-apis-worker.md) diff --git a/en/application-dev/reference/apis/apis.md b/en/application-dev/reference/apis/apis.md deleted file mode 100644 index c6e3221230b879b2f0dea7cffb27aa1b834914de..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/apis.md +++ /dev/null @@ -1,31 +0,0 @@ -# APIs - -- **[Console Logs](console-logs.md)** - -- **[HiAppEvent](hiappevent.md)** - -- **[Page Routing](page-routing.md)** - -- **[Pop-up Window](pop-up-window.md)** - -- **[Timer](timer.md)** - -- **[Audio Management](js-apis-audio.md)** - -- **[Audio Playback](audio-playback.md)** - -- **[Device Information](device-information.md)** - -- **[System Attribute](system-attribute.md)** - -- **[Battery and Charging](battery-and-charging.md)** - -- **[Screen Brightness](screen-brightness.md)** - -- **[Globalization](globalization.md)** - -- **[Resource Management](resource-management.md)** - -- **[Updater](updater.md)** - - diff --git a/en/application-dev/reference/apis/audio-playback.md b/en/application-dev/reference/apis/audio-playback.md deleted file mode 100644 index d15b3ff256a964a3cb1a70d901d2394012628b42..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/audio-playback.md +++ /dev/null @@ -1,452 +0,0 @@ -# Audio Playback - -## Modules to Import - -``` -import audio from '@ohos.multimedia.media'; -``` - -## Required Permissions - -None - -## Methods - -## createAudioPlayer\(\) - -Creates an **AudioPlayer** instance to control audio playback. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

AudioPlayer

-

Returns the AudioPlayer instance if the operation is successful; returns null otherwise.

-
- -**Example** - -``` -var audioplayer = audio.createAudioPlayer(); -``` - -## Appendixes - -## AudioPlayer - -Represents an audio player. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

src

-

string

-

Yes

-

Yes

-

URI of the audio resources

-

loop

-

boolean

-

Yes

-

Yes

-

Whether to loop audio playback

-

currentTime

-

number

-

Yes

-

No

-

Current playback position

-

duration

-

number

-

Yes

-

No

-

Playback duration

-

state

-

AudioState

-

Yes

-

No

-

Playback status

-
- -### play\(\) - -Starts audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; - -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### pause\(\) - -Pauses audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -} -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Start to pause audio playback.'); - audioplayer.pause(); -}; -audioplayer.on('pause', (err, action) => { - if (err) { - console.info('Error returned in the pause() callback.'); - return; - } - console.info('Succeeded in pausing audio playback.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### stop\(\) - -Stops audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Start to pause audio playback.'); - audioplayer.pause(); -}; -audioplayer.on('stop', (err, action) => { - if (err) { - console.info('Error returned in the stop() callback.'); - return; - } - console.info('Succeeded in stopping audio playback.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### seek\(number\) - -Goes to a specified playback position. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

timeMs

-

number

-

Yes

-

Target playback position

-
- -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.') -}; -audioplayer.on('timeUpdate', (seekTime, action) => { - console.info('Seek time returned in the seek() callback: ' + seekTime); - var newTime = audioplayer.currenTime; - if(newTime == 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.info('Seek failed.'); - } -}; -audioplayer.src = 'common/mydream.mp3'; -audioplayer.seek(30000); -``` - -### setVolume\(number\) - -Sets the volume. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

vol

-

number

-

Yes

-

Volume to set. The value ranges from 0 to 1.

-
- -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.error('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.error('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.') -}; -audioplayer.on('volumeChange', (err, action) => { - if (err) { - console.error('Error returned in the setVolume() callback.'); - return; - } - console.info('Playback volume changed.'); -}; -audioplayer.src = 'common/mydream.mp3'; -audioplayer.setVolume(0.5); -``` - -### reset\(\)7+ - -Switches the audio resource to be played. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.error('Error returned in the prepare() callback.'); - return; - } - console.info('Start to reset audio playback.'); - audioplayer.reset(); -}; -audioplayer.on('reset', (err, action) => { - if (err) { - console.error('Error returned in the reset() callback.'); - return; - } - console.info('Reset succeeded.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### release\(\) - -Releases audio resources. - -**Example** - -``` -audioplay.release(); -``` - -### Events - -### play - -Triggered when **play\(\)** is called - -### pause - -Triggered when **pause\(\)** is called - -### stop - -Triggered when **stop\(\)** is called - -### dataLoad - -Triggered when audio data is loaded - -### timeUpdate - -Triggered when the playback position changes - -### volumeChange - -Triggered when playback volume changes - -### finish - -Triggered when playback is finished - -### error - -Triggered when a playback error occurs - - - - - - - - - - - - -

Name

-

Type

-

Description

-

callback

-

ErrorCallback

-

Callback function for handling this event

-
- -## AudioState - -Describes playback status. - - - - - - - - - - - - - - - - - - - -

Name

-

Description

-

idle

-

Audio playback is idle.

-

playing

-

The audio is being played.

-

paused

-

Audio playback is paused.

-

stopped

-

Audio playback is stopped.

-
- diff --git a/en/application-dev/reference/apis/battery-and-charging.md b/en/application-dev/reference/apis/battery-and-charging.md deleted file mode 100644 index 4b19c60bfbec66451ad1f72489c5536f59b489c4..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/battery-and-charging.md +++ /dev/null @@ -1,245 +0,0 @@ -# Battery and Charging - -## Modules to Import - -``` -import batteryInfo from '@ohos.batteryinfo.d.ts' -``` - -## BatteryInfo - -Describes battery information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Readable/Writable

-

Type

-

Description

-

batterySOC

-

Read-only

-

number

-

Battery state of charge (SoC) of the current device

-

chargingStatus

-

Read-only

-

BatteryChargeState

-

Battery charging status of the current device

-

healthStatus

-

Read-only

-

BatteryHealthState

-

Battery health state of the current device

-

pluggedType

-

Read-only

-

BatteryPluggedType

-

Charger type of the current device

-

voltage

-

Read-only

-

number

-

Battery voltage of the current device

-

technology

-

Read-only

-

string

-

Battery technology of the current device

-

batteryTemperature

-

Read-only

-

number

-

Battery temperature of the current device

-
- -- Example - - ``` - import batteryInfo from '@ohos.batteryInfo'; - var batterySoc = batteryInfo.batterySOC; - ``` - - -## Enums - -## BatteryPluggedType - -Enumerates charger types. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown type

-

AC

-

1

-

AC charger

-

USB

-

2

-

USB charger

-

WIRELESS

-

3

-

Wireless charger

-
- -## BatteryChargeState - -Enumerates battery charging states. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown state

-

ENABLE

-

1

-

The battery is being charged.

-

DISABLE

-

2

-

The battery is not being charged.

-

FULL

-

3

-

The battery is fully charged.

-
- -## BatteryHealthState - -Enumerates battery health states. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

UNKNOWN

-

0

-

Unknown state

-

GOOD

-

1

-

The battery is in healthy state.

-

OVERHEAT

-

2

-

The battery is overheated.

-

OVERVOLTAGE

-

3

-

The battery voltage is over high.

-

COLD

-

4

-

The battery temperature is low.

-

DEAD

-

5

-

The battery is dead.

-
- diff --git a/en/application-dev/reference/apis/console-logs.md b/en/application-dev/reference/apis/console-logs.md deleted file mode 100644 index a8d9e8f9bf571e773805586225469f0596eb0599..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/console-logs.md +++ /dev/null @@ -1,54 +0,0 @@ -# Console Logs - -## Module to Import - -No module is required. - -## Permission List - -None - -## Log Category - -Prints a log using **console.debug|log|info|warn|error\(message\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print

-
- -- Example - - ``` - var versionCode = 1; - console.info('Hello World. The current version code is ' + versionCode); - ``` - - Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. - - ![](figures/log.png) - - > **NOTE:** - >The **console.log\(\)** function prints logs at the debug level. - - diff --git a/en/application-dev/reference/apis/device-information.md b/en/application-dev/reference/apis/device-information.md deleted file mode 100644 index fde4e698c126ab45f86a5e7313cbec6a941295a0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/device-information.md +++ /dev/null @@ -1,350 +0,0 @@ -# Device Information - -## Modules to Import - -``` -import deviceinfo from '@ohos.deviceinfo' -``` - -## Required Permissions - -None - -## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

deviceType

-

string

-

Yes

-

No

-

Device type

-

manufacture

-

string

-

Yes

-

No

-

Device manufacturer

-

brand

-

string

-

Yes

-

No

-

Device brand

-

marketName

-

string

-

Yes

-

No

-

External product series

-

productSeries

-

string

-

Yes

-

No

-

Product series

-

productModel

-

string

-

Yes

-

No

-

Product model

-

softwareModel

-

string

-

Yes

-

No

-

Software model

-

hardwareModel

-

string

-

Yes

-

No

-

Hardware model

-

hardwareProfile

-

string

-

Yes

-

No

-

Hardware profile

-

serial

-

string

-

Yes

-

No

-

Device serial number

-

bootloaderVersion

-

string

-

Yes

-

No

-

Bootloader version

-

abiList

-

string

-

Yes

-

No

-

Application binary interface (Abi) list

-

securityPatchTag

-

string

-

Yes

-

No

-

Security patch tag

-

displayVersion

-

string

-

Yes

-

No

-

Product version

-

incrementalVersion

-

string

-

Yes

-

No

-

Incremental version

-

osReleaseType

-

string

-

Yes

-

No

-

Release type. The options are as follows:

-
  • Canary: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
  • Beta: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
  • Release: Official release open to all developers. This release promises that all APIs are stable.
-

osFullName

-

string

-

Yes

-

No

-

OS version

-

majorVersion

-

number

-

Yes

-

No

-

Major version, incrementing along with OS version updates

-

seniorVersion

-

number

-

Yes

-

No

-

Senior version, incrementing along with architecture and feature updates

-

featureVersion

-

number

-

Yes

-

No

-

Feature version

-

buildVersion

-

number

-

Yes

-

No

-

Build version

-

sdkApiVersion

-

number

-

Yes

-

No

-

SDK API version

-

firstApiVersion

-

number

-

Yes

-

No

-

First API version

-

versionId

-

string

-

Yes

-

No

-

Version ID

-

buildType

-

string

-

Yes

-

No

-

Build type

-

buildUser

-

string

-

Yes

-

No

-

Build user

-

buildHost

-

string

-

Yes

-

No

-

Build host

-

buildTime

-

string

-

Yes

-

No

-

Build time

-

buildRootHash

-

string

-

Yes

-

No

-

Build root hash

-
- diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png new file mode 100644 index 0000000000000000000000000000000000000000..2128f0852380b2895198ab725a2f9d299c480d84 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png differ diff --git a/en/application-dev/reference/apis/globalization.md b/en/application-dev/reference/apis/globalization.md deleted file mode 100644 index e6640de0bc9868462efd74dee803a2c7783b3ba3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/globalization.md +++ /dev/null @@ -1,211 +0,0 @@ -# Globalization - - -## Imported Modules - -``` -import Intl from '@ohos.intl'; -``` - -## Permissions - -None. - -## Class - -## Locale - -Provides APIs for obtaining locale information. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

language

-

string

-

Yes

-

No

-

Indicates the language of the locale.

-

script

-

string

-

Yes

-

No

-

Indicates the script of the locale.

-

region

-

string

-

Yes

-

No

-

Indicates the region of the locale.

-

baseName

-

string

-

Yes

-

No

-

Indicates the basic locale information, which is returned as a substring of a complete locale string.

-
- -### Locale - -A constructor used to create a **Locale** object. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

locale

-

string

-

Yes

-

Indicates a character string containing the locale information, including the language and optionally the script and region.

-
- -**Example** - -``` -var enLatnGB = new Intl.Locale("en-Latn-GB"); -var enGB = new Intl.Locale("en-GB"); -var en = new Intl.Locale("en"); -``` - -## DateTimeFormat - -Provides the API for formatting date strings. - -### DateTimeFormat - -A constructor used to create a **DateTimeFormat** object. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

locale

-

string

-

Yes

-

Indicates a character string containing the locale information, including the language and optionally the script and region, for the DateTimeFormat object.

-
- -**Example** - -``` -var dateFmt = new Intl.DateTimeFormat("en-Latn-GB"); -``` - -### format - -Obtains the formatted date strings. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

date

-

Date

-

Yes

-

Indicates the Date object to be formatted.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

string

-

Indicates a date string formatted based on the specified locale.

-
- -**Example** - -``` -var date = new Date(1995, 11, 25, 3, 14, 0); -var datefmt = new Intl.DateTimeFormat("en-Latn-GB"); -var result = datefmt.format(date); // The formatted date string is Dec 25, 1995. -``` - diff --git a/en/application-dev/reference/apis/hiappevent.md b/en/application-dev/reference/apis/hiappevent.md deleted file mode 100644 index b762c810169941d54186ee5daef78652d2d7ddd0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/hiappevent.md +++ /dev/null @@ -1,358 +0,0 @@ -# HiAppEvent - -## Modules to Import - -``` -import hiappevent from '@ohos.hiappevent'; -``` - -## Required Permissions - -None. - -## Functions - -## write\(string, EventType, any..., AsyncCallback\) - -Writes event information to the event file of the current day. This function supports variable parameters and uses an asynchronous callback to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

params

-

any...

-

No

-

Indicates an array of parameters of the app event. Enter the name and value of each parameter in sequence. A parameter name must be a string, and a parameter value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-

callback

-

AsyncCallback<number>

-

No

-

Indicates the callback function, which can be used to process the received return value.

-
  • Value 0 indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value less than 0 indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.
-
- -**Example** - -``` -hiappevent.write("testEvent", hiappevent.EventType.FAULT, "intData", 100, "strData", "strValue", (err, value) => { - if (err) { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - return; - } - - // Event writing succeeded. - console.log(`success to write event: ${value}`); -}); -``` - -## write\(string, EventType, any...\) - -Writes event information to the event file of the current day. This function supports variable parameters and uses an asynchronous promise to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

params

-

any...

-

No

-

Indicates an array of parameters of the app event. Enter the name and value of each parameter in sequence. A parameter name must be a string, and a parameter value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Indicates the promise used to return the execution result.

-
- -**Example** - -``` -hiappevent.write("testEvent", hiappevent.EventType.FAULT, "intData", 100, "strData", "strValue") - .then((value) => { - // Event writing succeeded. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - }); -``` - -## writeJson\(string, EventType, object, AsyncCallback\) - -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

jsonParam

-

object

-

Yes

-

Indicates an array of JSON parameters of the app event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-

callback

-

AsyncCallback<number>

-

No

-

Indicates the callback function, which can be used to process the received return value.

-
  • Value 0 indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value less than 0 indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.
-
- -**Example** - -``` -hiappevent.writeJson("testEvent", hiappevent.EventType.FAULT, {"intData":100, "strData":"strValue"}, (err, value) => { - if (err) { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - return; - } - - // Event writing succeeded. - console.log(`success to write event: ${value}`); -}); -``` - -## writeJson\(string, EventType, object\) - -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous promise to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

jsonParam

-

object

-

Yes

-

Indicates an array of JSON parameters of the app event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Indicates the promise used to return the execution result.

-
- -**Example** - -``` -hiappevent.writeJson("testEvent", hiappevent.EventType.FAULT, {"intData":100, "strData":"strValue"}) - .then((value) => { - // Event writing succeeded. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - }); -``` - -## Enums - -## EventType - -Enumerates event types. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

FAULT

-

1

-

Fault event

-

STATISTIC

-

2

-

Statistical event

-

SECURITY

-

3

-

Security event

-

BEHAVIOR

-

4

-

System behavior event

-
- diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index facaa2410ce43a3d3b3858097fc660fe62eb10a4..6c7076e006a05fa06e709633f0e5e345265f9dca 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,26 +1,35 @@ # Audio Management - -## Modules to Import +## Modules to Import ``` import audio from '@ohos.multimedia.audio'; ``` -## Required Permissions +## Required Permissions None -## getAudioManager\(\): AudioManager +## getAudioManager\(\): AudioManager Obtains an **AudioManager** instance. **Return values** -| Type | Description | -| -------------- | -------------------------- | -| AudioManager | Audio manager. | - + + + + + + + + + +

Type

+

Description

+

AudioManager

+

Audio manager

+
**Example** @@ -28,84 +37,248 @@ Obtains an **AudioManager** instance. var audioManager = audio.getAudioManager(); ``` -## AudioVolumeType +## AudioVolumeType Enumerates audio stream types. -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| RINGTONE | 2 | Audio stream for ringtones. | -| MEDIA | 3 | Audio stream for media purpose. | - -## DeviceFlag + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

RINGTONE

+

2

+

Audio stream for ringtones

+

MEDIA

+

3

+

Audio stream for media purpose

+
+ +## DeviceFlag Enumerates audio device flags. -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| OUTPUT_DEVICES_FLAG | 1 | Output device. | -| INPUT_DEVICES_FLAG | 2 | Input device. | -| ALL_DEVICES_FLAG | 3 | All devices. | - - -## DeviceRole + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

OUTPUT_DEVICES_FLAG

+

1

+

Output device

+

INPUT_DEVICES_FLAG

+

2

+

Input device

+

ALL_DEVICES_FLAG

+

3

+

All devices

+
+ +## DeviceRole Enumerates audio device roles. -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| INPUT_DEVICE | 1 | Input role. | -| OUTPUT_DEVICE | 2 | Output role. | - -## DeviceType + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

INPUT_DEVICE

+

1

+

Input role

+

OUTPUT_DEVICE

+

2

+

Output role

+
+ +## DeviceType Enumerates audio device types. -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| INVALID | 0 | Invalid device. | -| EARPIECE | 1 | Earpiece. | -| SPEAKER | 2 | Speaker. | -| WIRED_HEADSET | 3 | Wired headset. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the synchronous connection oriented (SCO) link. | -| BLUETOOTH_A2DP | 8 | Bluetooth device using the advanced audio distribution profile (A2DP). | -| MIC | 15 | Microphone. | - - -## ActiveDeviceType7+ - -Enumerates active device types. - -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO link. | - -## AudioRingMode7+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

INVALID

+

0

+

Invalid device

+

SPEAKER

+

1

+

Speaker

+

WIRED_HEADSET

+

2

+

Wired headset

+

BLUETOOTH_SCO

+

3

+

Bluetooth device using the synchronous connection oriented (SCO) link

+

BLUETOOTH_A2DP

+

4

+

Bluetooth device using the advanced audio distribution profile (A2DP)

+

MIC

+

5

+

Microphone

+
+ +## AudioRingMode7+ Enumerates ringer modes. -| Name | Default Value | Description | -| ------------- | ------------- | --------------------------------------------------------------------- | -| RINGER_MODE_SILENT | 0 | Silence mode. | -| RINGER_MODE_VIBRATE | 1 | Vibration mode. | -| RINGER_MODE_NORMAL | 2 | Normal mode. | + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

RINGER_MODE_SILENT

+

0

+

Silence mode

+

RINGER_MODE_VIBRATE

+

1

+

Vibration mode

+

RINGER_MODE_NORMAL

+

2

+

Normal mode

+
## AudioManager Implements audio volume and audio device management. -### setVolume\(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void +### setVolume\(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void Sets the volume for a stream. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

volume

+

number

+

Yes

+

Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -123,22 +296,60 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{ }) ``` -### setVolume\(volumeType: AudioVolumeType, volume: number\): Promise +### setVolume\(volumeType: AudioVolumeType, volume: number\): Promise Sets the volume for a stream. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

volume

+

number

+

Yes

+

Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** @@ -148,16 +359,43 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=> ) ``` -### getVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +### getVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the volume of a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the volume

+
**Return values** @@ -175,21 +413,51 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getVolume\(volumeType: AudioVolumeType\): Promise +### getVolume\(volumeType: AudioVolumeType\): Promise Obtains the volume of a stream. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the volume. | + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the volume

+
**Example** @@ -199,16 +467,43 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### getMinVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +### getMinVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the minimum volume allowed for a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the minimum volume. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the minimum volume

+
**Return values** @@ -226,41 +521,97 @@ audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getMinVolume\(volumeType: AudioVolumeType\): Promise +### getMinVolume\(volumeType: AudioVolumeType\): Promise Obtains the minimum volume allowed for a stream. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the minimum volume. | - + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the minimum volume

+
**Example** ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => - console.log('Promised returned to indicate that the minimum volume is obtained.' + value); + console.log('Promised returned to indicate that the minimum volume is obtained.' + value); ) ``` -### getMaxVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +### getMaxVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the maximum volume allowed for a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the maximum volume. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the maximum volume

+
**Return values** @@ -278,22 +629,51 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getMaxVolume\(volumeType: AudioVolumeType\): Promise +### getMaxVolume\(volumeType: AudioVolumeType\): Promise Obtains the maximum volume allowed for a stream. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | - + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the maximum volume. | + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the maximum volume

+
**Example** @@ -303,17 +683,52 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=> ) ``` -### mute\(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void7+ +### mute\(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void7+ Mutes a stream. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the stream, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -331,22 +746,60 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }) ``` -### mute\(volumeType: AudioVolumeType, mute: boolean\): Promise7+ +### mute\(volumeType: AudioVolumeType, mute: boolean\): Promise7+ Mutes a stream. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the stream, and false means the opposite.

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** @@ -356,16 +809,43 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => ) ``` -### isMute\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ +### isMute\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ Checks whether a stream is muted. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

+
**Return values** @@ -383,22 +863,51 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### isMute\(volumeType: AudioVolumeType\): Promise7+ +### isMute\(volumeType: AudioVolumeType\): Promise7+ Checks whether a stream is muted. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | - + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

+
**Example** @@ -408,16 +917,43 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### isActive\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ +### isActive\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ Checks whether a stream is active. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

+
**Return values** @@ -435,22 +971,51 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### isActive\(volumeType: AudioVolumeType\): Promise7+ +### isActive\(volumeType: AudioVolumeType\): Promise7+ Checks whether a stream is active. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type

+
**Return values** - -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

+
**Example** @@ -460,16 +1025,43 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### setRingerMode\(mode: AudioRingMode, callback: AsyncCallback\): void7+ +### setRingerMode\(mode: AudioRingMode, callback: AsyncCallback\): void7+ Sets the ringer mode. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mode | AudioRingMode | Yes | Ringer mode. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mode

+

AudioRingMode

+

Yes

+

Ringer mode

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -487,22 +1079,51 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { }) ``` -### setRingerMode\(mode: AudioRingMode\): Promise7+ +### setRingerMode\(mode: AudioRingMode\): Promise7+ Sets the ringer mode. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mode | AudioRingMode | Yes | Ringer mode. | - + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mode

+

AudioRingMode

+

Yes

+

Ringer mode

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** @@ -512,15 +1133,34 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => ) ``` -### getRingerMode\(callback: AsyncCallback\): void7+ +### getRingerMode\(callback: AsyncCallback\): void7+ Obtains the ringer mode. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| callback | AsyncCallback<AudioRingMode> | Yes | Callback used to return the ringer mode. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<AudioRingMode>

+

Yes

+

Callback used to return the ringer mode

+
**Return values** @@ -538,7 +1178,7 @@ audioManager.getRingerMode((err, value) => { }) ``` -### getRingerMode\(\): Promise7+ +### getRingerMode\(\): Promise7+ Obtains the ringer mode. This method uses a promise to return the query result. @@ -548,9 +1188,20 @@ None **Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise<AudioRingMode> | Promise used to return the ringer mode. | + + + + + + + + + +

Type

+

Description

+

Promise<AudioRingMode>

+

Promise used to return the ringer mode

+
**Example** @@ -560,17 +1211,52 @@ audioManager.getRingerMode().then((value) => ) ``` -### setAudioParameter\(key: string, value: string, callback: AsyncCallback\): void7+ +### setAudioParameter\(key: string, value: string, callback: AsyncCallback\): void7+ Sets an audio parameter. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter to set

+

value

+

string

+

Yes

+

Value of the audio parameter to set

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -588,22 +1274,60 @@ audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { }) ``` -### setAudioParameter\(key: string, value: string\): Promise7+ +### setAudioParameter\(key: string, value: string\): Promise7+ Sets an audio parameter. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter to set

+

value

+

string

+

Yes

+

Value of the audio parameter to set

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** @@ -613,16 +1337,43 @@ audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => ) ``` -### getAudioParameter\(key: string, callback: AsyncCallback\): void7+ +### getAudioParameter\(key: string, callback: AsyncCallback\): void7+ Obtains the value of an audio parameter. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | -| callback | AsyncCallback | Yes | Callback used to return the value of the audio parameter. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter whose value is to be obtained

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback used to return the value of the audio parameter

+
**Return values** @@ -640,21 +1391,51 @@ audioManager.getAudioParameter('PBits per sample', (err, value) => { }) ``` -### getAudioParameter\(key: string\): Promise7+ +### getAudioParameter\(key: string\): Promise7+ Obtains the value of an audio parameter. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter whose value is to be obtained

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the value of the audio parameter. | + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the value of the audio parameter

+
**Example** @@ -664,16 +1445,43 @@ audioManager.getAudioParameter('PBits per sample').then((value) => ) ``` -### getDevices\(deviceFlag: DeviceFlag, callback: AsyncCallback\): void +### getDevices\(deviceFlag: DeviceFlag, callback: AsyncCallback\): void Obtains the audio devices with a specific flag. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceFlag | DeviceFlag | Yes | Audio device flag. | -| callback | AsyncCallback<AudioDeviceDescriptors> | Yes | Callback used to return the device list. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceFlag

+

DeviceFlag

+

Yes

+

Audio device flag

+

callback

+

AsyncCallback<AudioDeviceDescriptors>

+

Yes

+

Callback used to return the device list

+
**Return values** @@ -691,21 +1499,51 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ }) ``` -### getDevices\(deviceFlag: DeviceFlag\): Promise +### getDevices\(deviceFlag: DeviceFlag\): Promise Obtains the audio devices with a specific flag. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceFlag | DeviceFlag | Yes | Audio device flag. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceFlag

+

DeviceFlag

+

Yes

+

Audio device flag

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise<AudioDeviceDescriptors> | Promise used to return the device list. | + + + + + + + + + +

Type

+

Description

+

Promise<AudioDeviceDescriptors>

+

Promise used to return the device list

+
**Example** @@ -715,17 +1553,52 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=> ) ``` -### setDeviceActive\(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback\): void7+ +### setDeviceActive\(deviceType: DeviceType, active: boolean, callback: AsyncCallback\): void7+ Sets a device to the active state. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value **true** means to set the device to the active status, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type

+

active

+

boolean

+

Yes

+

Active status to set. The value true means to set the device to the active status, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -734,7 +1607,7 @@ None **Example** ``` -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err)=> { +audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> { if (err) { console.error('Failed to set the active status of the device. ${err.message}'); return; @@ -743,41 +1616,106 @@ audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err)=> { }) ``` -### setDeviceActive\(deviceType: ActiveDeviceType, active: boolean\): Promise7+ +### setDeviceActive\(deviceType: DeviceType, active: boolean\): Promise7+ Sets a device to the active state. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value **true** means to set the device to the active status, and **false** means the opposite. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type

+

active

+

boolean

+

Yes

+

Active status to set. The value true means to set the device to the active status, and false means the opposite.

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** ``` -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(()=> +audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=> console.log('Promise returned to indicate that the device is set to the active status.'); ) ``` -### isDeviceActive\(deviceType: DeviceType, callback: AsyncCallback\): void7+ +### isDeviceActive\(deviceType: DeviceType, callback: AsyncCallback\): void7+ Checks whether a device is active. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the device. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the active status of the device

+
**Return values** @@ -786,7 +1724,7 @@ None **Example** ``` -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { +audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => { if (err) { console.error('Failed to obtain the active status of the device. ${err.message}'); return; @@ -795,41 +1733,97 @@ audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { }) ``` -### isDeviceActive\(deviceType: ActiveDeviceType\): Promise7+ +### isDeviceActive\(deviceType: DeviceType\): Promise7+ Checks whether a device is active. This method uses a promise to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | - + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the active status of the device. | + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the active status of the device

+
**Example** ``` -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => +audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) => console.log('Promise returned to indicate that the active status of the device is obtained.' + value); ) ``` -### setMicrophoneMute\(mute: boolean, callback: AsyncCallback\): void7+ +### setMicrophoneMute\(mute: boolean, callback: AsyncCallback\): void7+ Mutes or unmutes the microphone. This method uses an asynchronous callback to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the microphone, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result

+
**Return values** @@ -847,21 +1841,51 @@ audioManager.setMicrophoneMute(true, (err) => { }) ``` -### setMicrophoneMute\(mute: boolean\): Promise7+ +### setMicrophoneMute\(mute: boolean\): Promise7+ Mutes or unmutes the microphone. This method uses a promise to return the execution result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the microphone, and false means the opposite.

+
**Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the execution result

+
**Example** @@ -871,15 +1895,34 @@ audioManager.setMicrophoneMute(true).then(() => ) ``` -### isMicrophoneMute\(callback: AsyncCallback\): void7+ +### isMicrophoneMute\(callback: AsyncCallback\): void7+ Checks whether the microphone is muted. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

+
**Return values** @@ -897,7 +1940,7 @@ audioManager.isMicrophoneMute((err, value) => { }) ``` -### isMicrophoneMute\(\): Promise7+ +### isMicrophoneMute\(\): Promise7+ Checks whether the microphone is muted. This method uses a promise to return the query result. @@ -907,9 +1950,20 @@ None **Return values** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

+
**Example** @@ -919,21 +1973,64 @@ audioManager.isMicrophoneMute().then((value) => ) ``` -## AudioDeviceDescriptor +## AudioDeviceDescriptor Describes an audio device. -### Attributes - -| Name | Type | Readable | Writable | Description | -| ------------- | ------------- | ---------------|--------------------------------|------------------------ | -| deviceRole | DeviceRole | Yes | No | Audio device role. | -| deviceType | DeviceType | Yes | No | Audio device type. | - -## AudioDeviceDescriptors - -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Device attribute array | Array of **AudioDeviceDescriptors**, which is read-only. | - +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

deviceRole

+

DeviceRole

+

Yes

+

No

+

Audio device role

+

deviceType

+

DeviceType

+

Yes

+

No

+

Audio device type

+
+ +## AudioDeviceDescriptors + + + + + + + + + + +

Name

+

Description

+

Device attribute array

+

Array of AudioDeviceDescriptors, which is read-only

+
diff --git a/en/application-dev/reference/apis/js-apis-basic-features-animator.md b/en/application-dev/reference/apis/js-apis-basic-features-animator.md new file mode 100644 index 0000000000000000000000000000000000000000..b259fe732e26348601c1d7a8e8a5002abe2a8a2b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-animator.md @@ -0,0 +1,479 @@ +# Animation + +>![](../../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. + +## Modules to Import + +**requestAnimationFrame**: none + +**cancelAnimationFrame**: none + +**createAnimator**: + +``` +import animator from '@ohos.animator'; +``` + +## Required Permissions + +None + +## requestAnimationFrame + +requestAnimationFrame\(handler\[, \[ ...args\]\]\): number + +Requests an animation frame. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Handler used to request a frame. When requestAnimationFrame calls the handler, the timestamp is passed to the first parameter to indicate the time when requestAnimationFrame starts to execute the callback.

+

...args

+

Array<any>

+

No

+

Additional parameter, which is passed to the handler as a parameter during function callback.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Request ID.

+
+ +- Example + + ``` + +
+ +
+ ``` + + ``` + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; + } + .btn{ + width: 300px; + margin-top: 40px; + } + ``` + + ``` + /* xxx.js */ + export default { + data: { + requestId: 0, + startTime: 0, + }, + beginAnimation() { + cancelAnimationFrame(this.requestId); + this.requestId = requestAnimationFrame(this.runAnimation); + }, + runAnimation(timestamp) { + if (this.startTime == 0) { + this.startTime = timestamp; + } + var elapsed = timestamp - this.startTime; + if (elapsed < 500) { + console.log('callback handler timestamp: ' + timestamp); + this.requestId = requestAnimationFrame(this.runAnimation); + } + } + } + ``` + + +## cancelAnimationFrame + +cancelAnimationFrame\(requestId: number\): void + +Cancels the animation frame request. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

requestId

+

number

+

Yes

+

ID of the frame request.

+
+ +- Example + + ``` + +
+ + +
+ ``` + + ``` + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; + } + .btn{ + width: 300px; + margin-top: 40px; + } + ``` + + ``` + /* xxx.js */ + export default { + data: { + requestId: 0, + startTime: 0, + }, + beginAnimation() { + cancelAnimationFrame(this.requestId); + this.requestId = requestAnimationFrame(this.runAnimation); + }, + runAnimation(timestamp) { + if (this.startTime == 0) { + this.startTime = timestamp; + } + var elapsed = timestamp - this.startTime; + if (elapsed < 500) { + console.log('callback handler timestamp: ' + timestamp); + this.requestId = requestAnimationFrame(this.runAnimation); + } + }, + stopAnimation() { + cancelAnimationFrame(this.requestId); + } + } + ``` + + +## createAnimator + +createAnimator\(options\[...\]\): void + +Creates an animation object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

options

+

Object

+

Yes

+

Attributes of the Animator to be created. For details, see the options table.

+
+ +- Description of options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

No

+

Duration for playing an animation, in milliseconds. The default value is 0.

+

easing

+

string

+

No

+

Animation easing curve. The default value is ease.

+

delay

+

number

+

No

+

Animation delay duration, in milliseconds. The default value is 0, indicating that there is no delay.

+

fill

+

string

+

No

+

Animation start/stop mode. The default value is none. For details, see animation-fill-mode.

+

direction

+

string

+

No

+

Animation playback mode. The default value is normal. For details, see animation-direction.

+

iterations

+

number

+

No

+

Number of times that an animation is played. The default value is 1. If this parameter is set to 0, the animation is not played. If this parameter is set to -1, the animation is played for an unlimited number of times.

+

begin

+

number

+

No

+

Start point of the animation easing. If this parameter is not set, the default value 0 is used.

+

end

+

number

+

No

+

End point of the animation easing. If this parameter is not set, the default value 1 is used.

+
+ +- animator interfaces + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

update

+

options

+

Updates the animation parameters. The input parameters are the same as those of createAnimator.

+

play

+

-

+

Starts an animation.

+

finish

+

-

+

Ends an animation.

+

pause

+

-

+

Pauses an animation.

+

cancel

+

-

+

Cancels an animation.

+

reverse

+

-

+

Reverses an animation.

+
+ + +- **animator** supported events: + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

frame

+

number

+

The frame is requested.

+

cancel

+

-

+

The animation is forcibly canceled.

+

finish

+

-

+

The animation playback is complete.

+

repeat

+

-

+

The animation replays.

+
+ +- Example + + ``` + +
+
+
+
+ ``` + + ``` + // js + export default { + data : { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + var options = { + duration: 1500, + easing: 'friction', + fill: 'forwards', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.createAnimator(options); + }, + Show() { + var options1 = { + duration: 2000, + easing: 'friction', + fill: 'forwards', + iterations: 1, + begin: 200.0, + end: 400.0 + }; + this.animator.update(options1); + var _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-app-context.md b/en/application-dev/reference/apis/js-apis-basic-features-app-context.md new file mode 100644 index 0000000000000000000000000000000000000000..01ee2571a8fb5275a2099acbca13458e8a561e32 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-app-context.md @@ -0,0 +1,89 @@ +# Application Context + +## Module to Import + +``` +import app from '@system.app'; +``` + +## Required Permissions + +None + +## app.getInfo + +getInfo\(\): <[AppResponse](#t3e93239d9b134b80957bcdd4acb05291)\> + +Obtains the declared information in the **config.json** file of an application. + +- Return values + + **Table 1** AppResponse + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

appID6+

+

string

+

Bundle name of the application. It uniquely identifies the application.

+

appName

+

string

+

Application name

+

versionName

+

string

+

Application version name

+

versionCode

+

number

+

Application version

+
+ +- Example + + ``` + export default { + getInfo(){ + var info = app.getInfo(); + console.log(JSON.stringify(info)); + } + } + ``` + + +## app.terminate + +terminate\(\): void + +Destroys the current ability. + +- Example + + ``` + export default { + terminate(){ + app.terminate(); + }} + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-configuration.md b/en/application-dev/reference/apis/js-apis-basic-features-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..4980558fae443cc47c6931e30c73d26fc77ef5d0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-configuration.md @@ -0,0 +1,77 @@ +# Application Configuration + +## Module to Import + +``` +import configuration from '@system.configuration'; +``` + +## Required Permissions + +None + +## configuration.getLocale + +getLocale\(\): <[LocaleResponse](#table1544853546)\> + +Obtains the current locale of the application, which is the same as the system locale. + +- Return values + + **Table 1** LocaleResponse + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

language

+

string

+

Current language of the application, for example, zh.

+

countryOrRegion

+

string

+

Country or region, for example, CN.

+

dir

+

string

+

Text layout direction. Available values are as follows:

+
  • ltr: The text direction is from left to right.
  • rtl: The text direction is from right to left.
+

unicodeSetting5+

+

string

+

Unicode key set determined by the locale.

+

For example, {"nu":"arab"} indicates that the current locale uses Arabic numerals.

+

If the current locale does not have a specific key set, an empty set is returned.

+
+ +- Example + + ``` + export default { + getLocale() { + const localeInfo = configuration.getLocale(); + console.info(localeInfo.language); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-logs.md b/en/application-dev/reference/apis/js-apis-basic-features-logs.md new file mode 100644 index 0000000000000000000000000000000000000000..864ce3ecc2e4ff92feebd0079fb597d8d55ee264 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-logs.md @@ -0,0 +1,188 @@ +# Console Logs + +## Module to Import + +No module is required. + +## Required Permissions + +None + +## console.debug + +debug\(message: string\): void + +Prints debug logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.log + +log\(message: string\): void + +Prints debug logs. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.info + +info\(message: string\): void + +Prints info-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.warn + +warn\(message: string\): void + +Prints warn-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.error + +error\(message: string\): void + +Prints error-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## Example + +``` +export default { + clickConsole(){ + var versionCode = 1; + console.info('Hello World. The current version code is ' + versionCode); + console.log(`versionCode: ${versionCode}`); + // The following is supported since API version 6. + console.log('versionCode:%d.', versionCode); + } +} +``` + +Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. + +![](figures/log.png) + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md b/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md new file mode 100644 index 0000000000000000000000000000000000000000..eefc43e94dd0fcedc89e03850d2b431b6d8dd0b1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md @@ -0,0 +1,322 @@ +# Pop-up Window + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Module to Import + +``` +import prompt from '@system.prompt'; +``` + +## Required Permissions + +None + +## prompt.showToast + +showToast\(Object\): void + +Displays the toast dialog box. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to display.

+

duration

+

number

+

No

+

Duration of the toast dialog box. The default value is 1500. The recommended value ranges from 1500 ms to 10000 ms.

+
NOTE:

A value less than 1500 is automatically changed to 1500. The maximum value is 10000 ms.

+
+

[bottom]5+

+

<length>

+

No

+

Distance between the dialog border and the bottom of the screen.

+
NOTE:

This parameter is only supported on phones and tablets.

+
+
+ +- Example + + ``` + export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } + } + ``` + + +## prompt.showDialog + +showDialog\(\): void + +Displays the dialog box. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

title

+

string

+

No

+

Title of the text to display.

+

message

+

string

+

No

+

Text body.

+

buttons

+

Array

+

No

+

Array of buttons in the dialog box. The array structure is {text:'button', color: '#666666'}. One to three buttons are supported. The first button is of the positiveButton type, the second is of the negativeButton type, and the third is of the neutralButton type.

+

success

+

Function

+

No

+

Called when the dialog box is displayed. For the return value, see return values of the success callback.

+

cancel

+

Function

+

No

+

Called when the operation is cancelled.

+

complete

+

Function

+

No

+

Called when the dialog box is closed.

+
+ + Return values of the **success** callback + + + + + + + + + + + + +

Parameter

+

Type

+

Description

+

index

+

number

+

Index of the selected button in the buttons array

+
+ +- Example + + ``` + export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button', + color: '#666666', + }, + ], + success: function(data) { + console.log('dialog success callback,click button : ' + data.index); + }, + cancel: function() { + console.log('dialog cancel callback'); + }, + }); + } + } + ``` + + +## prompt.showActionMenu6+ + +showActionMenu\(Object\): void + +Displays the operation menu. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

title

+

string

+

No

+

Title of the text to display.

+

buttons

+

Array

+

Yes

+

Array of buttons in the dialog box. The array structure is {text:'button', color: '#666666'}. One to six buttons are supported. If there are more than six buttons, the pop-up window will not be displayed.

+

success

+

(data: TapIndex) => void

+

No

+

Called when the operation is successful.

+

cancel

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ + **Table 1** TapIndex + + + + + + + + + + + + +

Name

+

Type

+

Description

+

tapIndex

+

number

+

Index of the selected button in the buttons array, starting from 0.

+
+ +- Example + + ``` + export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ], + success: function(data) { + console.log('Operation succeeded. Click button: ' + data.tapIndex); + }, + fail: function(data) { + console.log('Operation failed' + data.errMsg); + }, + }); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-routes.md b/en/application-dev/reference/apis/js-apis-basic-features-routes.md new file mode 100644 index 0000000000000000000000000000000000000000..b11f4372be2e27168601d9257285065649be1ad2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-routes.md @@ -0,0 +1,492 @@ +# Page Routing + +>![](../../public_sys-resources/icon-notice.gif) **NOTICE:** +>Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. + +## Module to Import + +``` +import router from '@system.router'; +``` + +## Required Permissions + +None. + +## router.push + +push\(Object\): void + +Navigates to a specified page in the application based on the page URL and parameters. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

Yes

+

URI of the destination page, in either of the following formats:

+
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    +
  • Particular path. If the URI is a slash (/), the home page is displayed.
+

params

+

Object

+

No

+

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

+
+ +- Example + + ``` + // Example code for the current page + export default { + pushPage() { + router.push({ + uri: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } + } + // Example code for the routerpage2 page + export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } + } + ``` + + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >The page routing stack supports a maximum of 32 pages. + + +## router.replace + +replace\(Object\): void + +Replaces the current page with another one in the application and destroys the current page. + +- Parameter + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

Yes

+

URI of the destination page, in either of the following formats:

+
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    +
  • Particular path. If the URI is a slash (/), the home page is displayed.
+

params

+

Object

+

No

+

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

+
+ +- Example + + ``` + // Example code for the current page + export default { + replacePage() { + router.replace({ + uri: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + // Example code for the detail page + export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } + } + ``` + + +## router.back + +back\(Object\): void + +Returns to the previous page or a specified page. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

No

+

URI of the page to return to. If the specified page does not exist in the page stack, the app does not respond. If this parameter is not set, the app returns to the previous page.

+
+ +- Example + + ``` + // index page + export default { + indexPushPage() { + router.push({ + uri: 'pages/detail/detail', + }); + } + } + + // detail page + export default { + detailPushPage() { + router.push({ + uri: 'pages/mall/mall', + }); + } + } + + // Navigate from the mall page to the detail page through router.back(). + export default { + mallBackPage() { + router.back(); + } + } + // Navigate from the detail page to the index page through router.back(). + export default { + defaultBack() { + router.back(); + } + } + // Return to the detail page through router.back(). + export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } + } + ``` + + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. + + +## router.clear + +clear\(\): void + +Clears all historical pages and retains only the current page at the top of the stack. + +- Example + + ``` + export default { + clearPage() { + router.clear(); + } + } + ``` + + +## router.getLength + +getLength\(\): string + +Obtains the number of pages in the current stack. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Number of pages in the stack. The maximum value is 32.

+
+ +- Example + + ``` + export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } + } + ``` + + +## router.getState + +getState\(\): <[RouterState](#tf9e3eb9ef0aa4d9880f996fe6afa6d1b)\> + +Obtains information about the current page state. + +- Return values + + **Table 1** RouterState + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

index

+

number

+

Index of the current page in the stack.

+
NOTE:

The index starts from 1 from the bottom to the top of the stack.

+
+

name

+

string

+

Name of the current page, that is, the file name.

+

path

+

string

+

Path of the current page.

+
+ +- Example + + ``` + export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } + } + ``` + + +## router.enableAlertBeforeBackPage6+ + +enableAlertBeforeBackPage\(Object\): void + +Enables the display of a confirm dialog for returning to the previous page. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Content of the confirm dialog.

+

success

+

() => void

+

No

+

Called when the operation is successful.

+

fail

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ +- Example + + ``` + export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` + + +## router.disableAlertBeforeBackPage6+ + +disableAlertBeforeBackPage\(Object\): void + +Disables the display of a confirm dialog for returning to the previous page. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

success

+

() => void

+

No

+

Called when the operation is successful.

+

fail

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ +- Example + + ``` + export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage({ + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-timer.md b/en/application-dev/reference/apis/js-apis-basic-features-timer.md new file mode 100644 index 0000000000000000000000000000000000000000..a7265c4972c52318d2f624939e935e56abdb2e63 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-timer.md @@ -0,0 +1,261 @@ +# Timer + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Module to Import + +None + +## Required Permissions + +None + +## setTimeout + +setTimeout\(handler\[,delay\[, ...args\]\]\): number + +Sets a timer for the system to call a function after the timer goes off. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Function to be called after the timer goes off.

+

delay

+

number

+

No

+

Number of milliseconds delayed before the execution. If this parameter is left empty, the default value 0 is used, which means that the execution starts immediately or as soon as possible.

+

...args

+

Array<any>

+

No

+

Additional parameter to pass to the handler after the timer goes off.

+
+ +- Return Value + + + + + + + + + + +

Type

+

Description

+

number

+

Timer ID.

+
+ +- Example + + ``` + export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); + } + } + ``` + + +## clearTimeout + +clearTimeout\(timeoutID: number\): void + +Cancels the timer created via **setTimeout\(\)**. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timeoutID

+

number

+

Yes

+

ID of the timer to cancel, which is returned by setTimeout()

+
+ +- Example + + ``` + export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); + } + } + ``` + + +## setInterval + +setInterval\(handler\[, delay\[, ...args\]\]\): number + +Sets a repeating timer for the system to repeatedly call a function at a fixed interval. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Function to be called repeatedly

+

delay

+

number

+

No

+

Number of milliseconds delayed before the execution

+

...args

+

Array<any>

+

No

+

Additional parameter to pass to the handler after the timer goes off

+
+ +- Return Value + + + + + + + + + + +

Type

+

Description

+

number

+

ID of the repeated timer.

+
+ +- Example + + ``` + export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + } + } + ``` + + +## clearInterval + +clearInterval\(intervalID: number\): void + +Cancels the repeating timer set via **setInterval\(\)**. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

intervalID

+

number

+

Yes

+

ID of the repeating timer to cancel, which is returned by setInterval().

+
+ +- Example + + ``` + export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md new file mode 100644 index 0000000000000000000000000000000000000000..64b8115fac736b6f41a5825b8f5a89bf5ed3e21c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -0,0 +1,273 @@ +# Battery Info + +>![](../../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. + +## Modules to Import + +``` +import batteryInfo from '@ohos.batteryInfo'; +``` + +## Attributes + +Describes battery information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

batterySOC

+

number

+

Yes

+

No

+

Battery state of charge (SoC) of the current device.

+

chargingStatus

+

BatteryChargeState

+

Yes

+

No

+

Battery charging state of the current device.

+

healthStatus

+

BatteryHealthState

+

Yes

+

No

+

Battery health state of the current device.

+

pluggedType

+

BatteryPluggedType

+

Yes

+

No

+

Charger type of the current device.

+

voltage

+

number

+

Yes

+

No

+

Battery voltage of the current device.

+

technology

+

string

+

Yes

+

No

+

Battery technology of the current device.

+

batteryTemperature

+

number

+

Yes

+

No

+

Battery temperature of the current device.

+

isBatteryPresent7+

+

boolean

+

Yes

+

No

+

Whether the battery is supported or present.

+
+ +- Example + + ``` + import batteryInfo from '@ohos.batteryInfo'; + var batterySoc = batteryInfo.batterySOC; + ``` + + +## BatteryPluggedType + +Enumerates charger types. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

NONE

+

0

+

Unknown type

+

AC

+

1

+

AC charger

+

USB

+

2

+

USB charger

+

WIRELESS

+

3

+

Wireless charger

+
+ +## BatteryChargeState + +Enumerates charging states. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

NONE

+

0

+

Unknown state.

+

ENABLE

+

1

+

The battery is being charged.

+

DISABLE

+

2

+

The battery is not being charged.

+

FULL

+

3

+

The battery is fully charged.

+
+ +## BatteryHealthState + +Enumerates battery health states. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

UNKNOWN

+

0

+

Unknown state.

+

GOOD

+

1

+

The battery is in the healthy state.

+

OVERHEAT

+

2

+

The battery is overheated.

+

OVERVOLTAGE

+

3

+

The battery voltage is over high.

+

COLD

+

4

+

The battery temperature is low.

+

DEAD

+

5

+

The battery is dead.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md new file mode 100644 index 0000000000000000000000000000000000000000..a4c533575f626f9b7c4dffb968da7809e0fe84e8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -0,0 +1,50 @@ +# Brightness + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import brightness from '@ohos.brightness'; +``` + +## brightness.setValue + +setValue\(value: number\) + +Sets the screen brightness. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Brightness value, ranging from 0 to 255

+
+ +- Example + + ``` + import brightness from '@ohos.brightness.d.ts'; + brightness.setValue(128); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md new file mode 100644 index 0000000000000000000000000000000000000000..25c7658cd4e43e13bed0a32245877b5a228ee70b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -0,0 +1,198 @@ +# Performance Tracing + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import bytrace from '@ohos.bytrace'; +``` + +## Required Permissions + +None + +## bytrace.startTrace + +startTrace\(name: string, taskId: number, expectedTime?: number\): void + +Starts a trace of a task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the trace task to start.

+

taskId

+

number

+

Yes

+

Task ID.

+

expectedTime

+

number

+

No

+

Expected duration of the trace, in ms.

+
+ + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different **taskId**s must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same **taskId** can be used. For details, see the **bytrace.finishTrace** example. + +- Example + + ``` + bytrace.startTrace("myTestFunc", 1); + bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms. + ``` + + +## bytrace.finishTrace + +finishTrace\(name: string, taskId: number\): void + +Stops a trace task. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the trace task to stop.

+

taskId

+

number

+

Yes

+

Task ID.

+
+ + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >To stop a trace task, the values of **name** and **taskId** in **finishTrace** must be the same as those in **startTrace**. + +- Example + + ``` + bytrace.finishTrace("myTestFunc", 1); + ``` + + ``` + // Start track tasks with the same name concurrently. + bytrace.startTrace("myTestFunc", 1); + ...... // Service flow + bytrace.startTrace ("myTestFunc", 2); // The second trace task starts while the first task is still running. The first and second tasks have the same name but different task IDs. + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); + ...... // Service flow + bytrace.finishTrace("myTestFunc", 2); + ``` + + ``` + // Start track tasks with the same name at different times. + bytrace.startTrace("myTestFunc", 1); + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); // The first trace task ends. + ...... // Service flow + bytrace.startTrace("myTestFunc", 1); // The second trace task starts after the first task ends. The two tasks have the same name and task ID. + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); + ``` + + +## bytrace.traceByValue + +traceByValue\(name: string, value: number\): void + +Traces the value changes of a variable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the variable to trace.

+

value

+

number

+

Yes

+

Value of the variable to trace.

+
+ +- Example + + ``` + let traceCount = 3; + bytrace.traceByValue("myTestCount", traceCount); + ...... + traceCount = 5; + bytrace.traceByValue("myTestCount", traceCount); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 16d5ceb279a670886be407b0f02e0b9a6a0b6e84..14584a1f0e3c2f9c700bb8afb0bee7168b867f24 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -2,9 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. -> ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..644c99095bc672618b63741551cbc4833e72dde5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -0,0 +1,1698 @@ +# DataAbilityPredicates + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import dataAbility from '@ohos.data.dataAbility' +``` + +## Required Permissions + +None + +## dataAbility.createRdbPredicates + +createRdbPredicates\(name: string, dataAbilityPredicates: DataAbilityPredicates\): rdb.RdbPredicates + +Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Table name in the RDB store.

+

dataAbilityPredicates

+

DataAbilityPredicates

+

Yes

+

DataAbilityPredicates object.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

rdb.RdbPredicates

+

RdbPredicates object created.

+
+ +- Example + + ``` + let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() + dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) + let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) + ``` + + +## DataAbilityPredicates + +Provides predicates for implementing diverse query methods. + +### equalTo + +equalTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + +notEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + +beginWrap\(\): DataAbilityPredicates + +Adds a left parenthesis to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with a left parenthesis.

+
+ +- Example + + ``` + let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + +endWrap\(\): DataAbilityPredicates + +Adds a right parenthesis to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with a right parenthesis.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + +or\(\): DataAbilityPredicates + +Adds the OR condition to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with the OR condition.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + +and\(\): DataAbilityPredicates + +Adds the AND condition to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates with the AND condition.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + +contains\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string containing the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + +beginsWith\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that starts with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + +endsWith\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that ends with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + +isNull\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field whose value is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + +isNotNull\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field whose value is not **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + +like\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that is similar to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + +glob\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the specified string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + +between\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the DataAbilityPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + +notBetween\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the DataAbilityPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + +greaterThan\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + +lessThan\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + +greaterThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + +lessThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + +orderByAsc\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the column with values sorted in ascending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the column sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + +orderByDesc\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the column with values sorted in descending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the column sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + +distinct\(\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to filter out duplicate records. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that can filter out duplicate records.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let resultSet = await rdbStore.query(predicates, ["NAME"]) + ``` + + +### limitAs + +limitAs\(value: number\): DataAbilityPredicates + +Set the **DataAbilityPredicates** that specify the maximum number of records. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Maximum number of records in a column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates that can be used to set the maximum number of records.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + +offsetAs\(rowOffset: number\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to specify the start position of the returned result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rowOffset

+

number

+

Yes

+

Number of rows to offset from the beginning. The value is a positive integer.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that specifies the start position of the returned result.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + +groupBy\(fields: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to group rows that have the same value into summary rows. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fields

+

Array<string>

+

Yes

+

Names of columns grouped for querying data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that groups rows that have the same value.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + + +### indexedBy + +indexedBy\(indexName: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to specify the index column. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

indexName

+

string

+

Yes

+

Name of the index column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityRdbPredicates object that specifies the index column.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + +in\(field: string, value: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **Array** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + +notIn\(field: string, value: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **Array** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md new file mode 100644 index 0000000000000000000000000000000000000000..2dff3ab63cb525e0916efaff8a84d4a2f553542b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -0,0 +1,2642 @@ +# Relational Database + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import dataRdb from '@ohos.data.rdb' +``` + +## Required Permissions + +None + +## dataRdb.getRdbStore + +getRdbStore\(config: StoreConfig, version: number, callback: AsyncCallback\): void + +Obtains a relational database \(RDB\) store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

StoreConfig

+

Yes

+

Configuration of the RDB store.

+

version

+

number

+

Yes

+

RDB store version.

+

callback

+

AsyncCallback<RdbStore>

+

Yes

+

Callback invoked to return the RDB store.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + const STORE_CONFIG = { name: "RdbTest.db" } + const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" + dataRdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info(TAG + 'create table done.') + }) + ``` + + +## dataRdb.getRdbStore + +getRdbStore\(config: StoreConfig, version: number\): Promise + +Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

StoreConfig

+

Yes

+

Configuration of the RDB store.

+

version

+

number

+

Yes

+

RDB store version.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<RdbStore>

+

Promise used to return the RDB store.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + const STORE_CONFIG = { name: "RdbTest.db" } + const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" + let promise = dataRdb.getRdbStore(STORE_CONFIG, 1); + promise.then(async (rdbStore) => { + await rdbStore.executeSql(SQL_CREATE_TABLE, null) + }).catch((err) => { + expect(null).assertFail(); + }) + ``` + + +## dataRdb.deleteRdbStore + +deleteRdbStore\(name: string, callback: AsyncCallback\): void + +Deletes an RDB store. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RDB store to delete.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + dataRdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { + console.info(TAG + 'delete store done.')}) + ``` + + +## dataRdb.deleteRdbStore + +deleteRdbStore\(name: string\): Promise + +Deletes an RDB store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RDB store to delete.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + let promise = dataRdb.deleteRdbStore("RdbTest.db") + promise.then(()=>{ + console.info(TAG + 'delete store done.') + }) + ``` + + +## RdbPredicates + +Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. + +### constructor + +constructor\(name: string\) + +A constructor used to create an **RdbPredicates** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Database table name.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + ``` + + +### equalTo + +equalTo\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + +notEqualTo\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + +beginWrap\(\): RdbPredicates + +Adds a left parenthesis to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with a left parenthesis.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + +endWrap\(\): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with a right parenthesis.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + +or\(\): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with the OR condition.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + +and\(\): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with the AND condition.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + +contains\(field: string, value: string\): RdbPredicat + +Sets the **RdbPredicates** to match a string containing the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + +beginsWith\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that starts with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + +endsWith\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that ends with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + +isNull\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the field whose value is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + +isNotNull\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the field whose value is not **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + +like\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that is similar to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + +glob\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match the specified string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + +between\(field: string, low: ValueType, high: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the RdbPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + +notBetween\(field: string, low: ValueType, high: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the RdbPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + +greaterThan\(field: string, value: ValueType\): RdbPredicatesgr + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + +lessThan\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + +greaterThanOrEqualTo\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + +lessThanOrEqualTo\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + +orderByAsc\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the column with values sorted in ascending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the column with values sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + +orderByDesc\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the column with values sorted in descending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the column with values sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + +distinct\(\): RdbPredicates + +Sets the **RdbPredicates** to filter out duplicate records. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that can filter out duplicate records.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let resultSet = await rdbStore.query(predicates, ["NAME"]) + ``` + + +### limitAs + +limitAs\(value: number\): RdbPredicates + +Sets the **RdbPredicates** to specify the maximum number of records. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Maximum number of records.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the maximum number of records.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + +offsetAs\(rowOffset: number\): RdbPredicates + +Sets the **RdbPredicates** to specify the start position of the returned result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rowOffset

+

number

+

Yes

+

Number of rows to offset from the beginning. The value is a positive integer.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the start position of the returned result.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + +groupBy\(fields: Array\): RdbPredicates + +Sets the **RdbPredicates** to group rows that have the same value into summary rows. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fields

+

Array<string>

+

Yes

+

Names of columns to group.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that groups rows with the same value.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + + +### indexedBy + +indexedBy\(indexName: string\): RdbPredicates + +Sets the **RdbPredicates** object to specify the index column. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

indexName

+

string

+

Yes

+

Name of the index column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the index column.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + +in\(field: string, value: Array\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **Array** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + +notIn\(field: string, value: Array\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **Array** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` + + +## RdbStore + +Provides methods to manage an RDB store. + +### insert + +insert\(name: string, values: ValuesBucket, callback: AsyncCallback\):void + +Inserts a row of data into a table. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the target table.

+

values

+

ValuesBucket

+

Yes

+

Row of data to insert.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback invoked to return the result. If the operation is successful, the row ID will be returned. If the operation fails, -1 will be returned.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { + expect(1).assertEqual(ret) + console.log(TAG + "insert first done: " + ret)}) + ``` + + +### insert + +insert\(name: string, values: ValuesBucket\):Promise + +Inserts a row of data into a table. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the target table.

+

values

+

ValuesBucket

+

Yes

+

Row of data to insert.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the result. If the operation is successful, the row ID will be returned. If the operation fails, -1 will be returned.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let promise = rdbStore.insert("EMPLOYEE", valueBucket) + promise.then(async (ret) => { + await console.log(TAG + "insert first done: " + ret) + }).catch((err) => {}) + ``` + + +### update + +update\(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback\):void + +Updates data in the database based on the specified **RdbPredicates** object. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

values

+

ValuesBucket

+

Yes

+

Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Row of data to insert.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the number of rows updated.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + rdbStore.update(valueBucket, predicates, function (err, ret) { + console.log(TAG + "updated row count: " + changedRows)}) + ``` + + +### update + +update\(values: ValuesBucket, rdbPredicates: RdbPredicates\):Promise + +Updates data in the database based on the specified **RdbPredicates** object. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

values

+

ValuesBucket

+

Yes

+

Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Row of data to insert.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the number of rows updated.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + let promise = rdbStore.update(valueBucket, predicates) + promise.then(async (ret) => { + await console.log(TAG + "updated row count: " + changedRows) + }).catch((err) => {}) + ``` + + +### delete + +delete\(rdbPredicates: RdbPredicates, callback: AsyncCallback\):void + +Deletes data from the database based on the specified **RdbPredicates** object. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Conditions specified for deleting data.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback invoked to return the number of rows deleted.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + rdbStore.delete(predicates, function (err, rows) { + console.log(TAG + "delete rows: " + rows)}) + ``` + + +### delete + +delete\(rdbPredicates: RdbPredicates\):Promise + +Deletes data from the database based on the specified **RdbPredicates** object. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Conditions specified for deleting data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the number of rows deleted.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + let promise = rdbStore.delete(predicates) + promise.then((rows) => { + console.log(TAG + "delete rows: " + rows) + }).catch((err) => {}) + ``` + + +### query + +query\(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback\):void + +Queries data in the database based on specified conditions. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Query conditions specified by the RdbPredicates object.

+

columns

+

Array<string>

+

Yes

+

Columns to query. If this parameter is not specified, the query applies to all columns.

+

callback

+

AsyncCallback<ResultSet>

+

Yes

+

Callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + console.log(TAG + "resultSet column names:" + resultSet.columnNames) + console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + ``` + + +### query + +query\(rdbPredicates: RdbPredicates, columns: Array\):Promise + +Queries data in the database based on specified conditions. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Query conditions specified by the RdbPredicates object.

+

columns

+

Array<string>

+

Yes

+

Columns to query. If this parameter is not specified, the query applies to all columns.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResultSet>

+

Promise used to return the result. If the operation is successful, a ResultSet object will be returned.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promise.then((resultSet) => { + console.log(TAG + "resultSet column names:" + resultSet.columnNames) + console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + ``` + + +### executeSql + +executeSql\(sql: string, bindArgs: Array, callback: AsyncCallback\):void + +Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

sql

+

string

+

Yes

+

SQL statement to run.

+

bindArgs

+

Array<ValueType>

+

Yes

+

Values of the parameters in the SQL statement.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ + +- Example + + ``` + rdbStore.executeSql("DELETE FROM EMPLOYEE", function () { + console.info(TAG + 'delete done.')}) + ``` + + +### executeSql + +executeSql\(sql: string, bindArgs: Array\):Promise + +Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

sql

+

string

+

Yes

+

SQL statement to run.

+

bindArgs

+

Array<ValueType>

+

Yes

+

Values of the parameters in the SQL statement.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + let promise = rdbStore.executeSql("DELETE FROM EMPLOYEE") + promise.then(() => { + console.info(TAG + 'delete done.')}) + ``` + + +## StoreConfig + +Manages the configuration of an RDB store. + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Database file name.

+
+ +## ValueType + +Defines the data types allowed. + + + + + + + + + + + + + + + + +

Name

+

Description

+

number

+

Number.

+

string

+

String.

+

boolean

+

Boolean.

+
+ +## ValuesBucket + +Defines a bucket to store key-value pairs. + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

[key: string]

+

ValueType| Uint8Array | null

+

Yes

+

Key-value pairs stored.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md new file mode 100644 index 0000000000000000000000000000000000000000..7e72ca266d54f2f9267a4c47f14da2693c81ff4f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -0,0 +1,788 @@ +# Result Set + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Usage + +The **resultSet** object is obtained by using [**RdbStore.query\(\)**](js-apis-data-rdb.md#section6231155031814). + +``` +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("AGE", 18) +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + await console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + await console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) +``` + +## Required Permissions + +None + +## ResultSet + +Provides methods to access the result set, which is obtained by querying the relational database \(RDB\) store. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnNames

+

Array<string>

+

Yes

+

Names of all columns in the result set.

+

columnCount

+

number

+

Yes

+

Number of columns in the result set.

+

rowCount

+

number

+

Yes

+

Number of rows in the result set.

+

rowIndex

+

number

+

Yes

+

Index of the current row in the result set.

+

isAtFirstRow

+

boolean

+

Yes

+

Specifies whether the cursor is in the first row of the result set.

+

isAtLastRow

+

boolean

+

Yes

+

Whether the cursor is in the last row of the result set.

+

isEnded

+

boolean

+

Yes

+

Whether the cursor is after the last row of the result set.

+

isStarted

+

boolean

+

Yes

+

Whether the cursor has been moved.

+

isClosed

+

boolean

+

Yes

+

Whether the result set is closed.

+
+ +### getColumnIndex + +getColumnIndex\(columnName: string\): number + +Obtains the column index based on the specified column name. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnName

+

string

+

Yes

+

Name of the column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Index of the column.

+
+ +- Example + + ``` + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("ID")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### getColumnName + +getColumnName\(columnIndex: number\): string + +Obtains the column name based on the specified column index. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the column.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Name of the column.

+
+ +- Example + + ``` + const id = resultSet.getColumnName(0) + const name = resultSet.getColumnName(1) + const age = resultSet.getColumnName(2) + ``` + + +### goTo + +goTo\(offset:number\): boolean + +Moves the cursor to the row based on the specified offset. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

offset

+

number

+

Yes

+

Offset relative to the current position.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goTo(1) + resultSet.close() + resultSet = null + ``` + + +### goToRow + +goToRow\(position: number\): boolean + +Moves the cursor to the specified row in the result set. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

position

+

number

+

Yes

+

Position to which the cursor is to be moved.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToRow(1) + resultSet.close() + resultSet = null + ``` + + +### goToFirstRow + +goToFirstRow\(\): boolean + +Moves the cursor to the first row of the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToFirstRow() + resultSet.close() + resultSet = null; + ``` + + +### goToLastRow + +goToLastRow\(\): boolean + +Moves the cursor to the last row of the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToLastRow() + resultSet.close() + resultSet = null; + ``` + + +### goToNextRow + +goToNextRow\(\): boolean + +Moves the cursor to the next row in the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToNextRow() + resultSet.close() + resultSet = null; + ``` + + +### goToPreviousRow + +goToPreviousRow\(\): boolean + +Moves the cursor to the previous row in the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToPreviousRow() + resultSet.close() + resultSet = null + ``` + + +### getBlob + +getBlob\(columnIndex: number\): Uint8Array + +Obtains the value in the specified column in the current row as a byte array. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Value in the specified column as a byte array.

+
+ +- Example + + ``` + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + ``` + + +### getString + +getString\(columnIndex: number\): string + +Obtains the value in the specified column in the current row as a string. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Value in the specified column as a string.

+
+ +- Example + + ``` + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + ``` + + +### getLong + +getLong\(columnIndex: number\): number + +Obtains the value in the specified column in the current row as a **Long**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Value in the specified column as a Long.

+
+ +- Example + + ``` + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + ``` + + +### getDouble + +getDouble\(columnIndex: number\): number + +Obtains the value in the specified column in the current row as a **double**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Value in the specified column as a double.

+
+ +- Example + + ``` + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### isColumnNull + +isColumnNull\(columnIndex: number\): boolean + +Checks whether the value in the specified column in the current row is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the value is null; returns false otherwise.

+
+ +- Example + + ``` + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + ``` + + +### close + +close\(\): void + +Closes the result set. + +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.close() + resultSet = null + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..e236b61478026960f226f367e4ecf3105c5f9e12 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -0,0 +1,1608 @@ +# Lightweight Storage + +Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the numeric, string, or Boolean type. + +>![](../../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. + +## Modules to Import + +``` +import dataStorage from '@ohos.data.storage' +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

MAX_KEY_LENGTH

+

string

+

Yes

+

No

+

Maximum length of a key. It is 80 bytes.

+

MAX_VALUE_LENGTH

+

string

+

Yes

+

No

+

Maximum length of a value of the string type. It is 8192 bytes.

+
+ +## dataStorage.getStorageSync + +getStorageSync\(path: string\): Storage + +Reads a specified file and loads the data to the **Storage** instance for data operations in synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Storage

+

Storage instance used for data storage operations

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let storage = dataStorage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() + ``` + + +## dataStorage.getStorage + +getStorage\(path: string, callback: AsyncCallback\): void + +Reads a specified file and loads the data to the **Storage** instance for data operations. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<Storage>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + dataStorage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + storage.putSync('startup', 'auto') + storage.flushSync() + }) + ``` + + +## dataStorage.getStorage + +getStorage\(path: string\): Promise + +Reads a specified file and loads the data to the **Storage** instance for data operations. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Storage>

+

Promise used to return the result.

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let promise = dataStorage.getStorage(path + '/mystore') + promise.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Get the storage failed, path: " + path + '/mystore') + }) + ``` + + +## dataStorage.deleteStorageSync + +deleteStorageSync\(path: string\): void + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Example: + + ``` + dataStorage.deleteStorageSync(path + '/mystore') + ``` + + +## dataStorage.deleteStorage + +deleteStorage\(path: string, callback: AsyncCallback\) + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses an asynchronous callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + dataStorage.deleteStorage(path + '/mystore', function (err) { + if (err) { + console.info("Deleted failed with err: " + err) + return + } + console.info("Deleted successfully.") + }) + ``` + + +## dataStorage.deleteStorage + +deleteStorage\(path: string\): Promise + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = dataStorage.deleteStorage(path + '/mystore') + promise.then(() => { + console.info("Deleted successfully.") + }).catch((err) => { + console.info("Deleted failed with err: " + err) + }) + ``` + + +## dataStorage.removeStorageFromCacheSync + +removeStorageFromCacheSync\(path: string\): void + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Example: + + ``` + dataStorage.removeStorageFromCacheSync(path + '/mystore') + ``` + + +## dataStorage.removeStorageFromCache + +removeStorageFromCache\(path: string, callback: AsyncCallback\): void + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<Storage>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + dataStorage.removeStorageFromCache(path + '/mystore', function (err) { + if (err) { + console.info("Removed storage from cache failed with err: " + err) + return + } + console.info("Removed storage from cache successfully.") + }) + ``` + + +## dataStorage.removeStorageFromCache + +removeStorageFromCache\(path: string\): Promise + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = dataStorage.removeStorageFromCache(path + '/mystore') + promise.then(() => { + console.info("Removed storage from cache successfully.") + }).catch((err) => { + console.info("Removed storage from cache failed with err: " + err) + }) + ``` + + +## Storage + +Provides APIs for obtaining and modifying storage data. + +### getSync + +getSync\(key: string, defValue: ValueType\): ValueType + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned if the value of the specified key does not exist. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

ValueType

+

Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.

+
+ +- Example: + + ``` + let value = storage.getSync('startup', 'default') + console.info("The value of startup is " + value) + ``` + + +### get + +get\(key: string, defValue: ValueType, callback: AsyncCallback\): void + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned. The value can be a number, string, or Boolean value.

+

callback

+

AsyncCallback<ValueType>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.get('startup', 'default', function(err, value) { + if (err) { + console.info("Get the value of startup failed with err: " + err) + return + } + console.info("The value of startup is " + value) + }) + ``` + + +### get + +get\(key: string, defValue: ValueType\): Promise + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ValueType>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.get('startup', 'default') + promise.then((value) => { + console.info("The value of startup is " + value) + }).catch((err) => { + console.info("Get the value of startup failed with err: " + err) + }) + ``` + + +### putSync + +putSync\(key: string, value: ValueType\): void + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+
+ +- Example: + + ``` + storage.putSync('startup', 'auto') + ``` + + +### put + +put\(key: string, value: ValueType, callback: AsyncCallback\): void + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.put('startup', 'auto', function (err) { + if (err) { + console.info("Put the value of startup failed with err: " + err) + return + } + console.info("Put the value of startup successfully.") + }) + ``` + + +### put + +put\(key: string, value: ValueType\): Promise + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.put('startup', 'auto') + promise.then(() => { + console.info("Put the value of startup successfully.") + }).catch((err) => { + console.info("Put the value of startup failed with err: " + err) + }) + ``` + + +### hasSync + +hasSync\(key: string\): boolean + +Checks whether the storage object contains data with the specified key. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the storage object contains data with the specified key; returns false otherwise.

+
+ +- Example: + + ``` + let isExist = storage.hasSync('startup') + if (isExist) { + console.info("The key of startup is contained.") + } + ``` + + +### has + +has\(key: string, callback: AsyncCallback\): boolean + +Checks whether the storage object contains data with the specified key. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the result.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the storage object contains data with the specified key; returns false otherwise.

+
+ +- Example: + + ``` + storage.has('startup', function (err, isExist) { + if (err) { + console.info("Check the key of startup failed with err: " + err) + return + } + if (isExist) { + console.info("The key of startup is contained.") + } + }) + ``` + + +### has + +has\(key: string\): Promise + +Checks whether the storage object contains data with the specified key. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.has('startup') + promise.then((isExist) => { + if (isExist) { + console.info("The key of startup is contained.") + } + }).catch((err) => { + console.info("Check the key of startup failed with err: " + err) + }) + ``` + + +### deleteSync + +deleteSync\(key: string\): void + +Deletes the data with the specified key from this storage object. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Example: + + ``` + storage.deleteSync('startup') + ``` + + +### delete + +delete\(key: string, callback: AsyncCallback\): void + +Deletes the data with the specified key from this storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.delete('startup', function (err) { + if (err) { + console.info("Delete startup key failed with err: " + err) + return + } + console.info("Deleted startup key successfully.") + }) + ``` + + +### delete + +delete\(key: string\): Promise + +Deletes the data with the specified key from this storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.delete('startup') + promise.then(() => { + console.info("Deleted startup key successfully.") + }).catch((err) => { + console.info("Delete startup key failed with err: " + err) + }) + ``` + + +### flushSync + +flushSync\(\): void + +Saves the modification of the current object to the current **Storage** instance and synchronizes the modification to the file. + +This method uses a synchronous mode. + +- Example: + + ``` + storage.flushSync() + ``` + + +### flush + +flush\(callback: AsyncCallback\): void + +Saves the modification of the current object to the current **Storage** instance and stores the modification to the file in an asynchronous mode. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.flush(function (err) { + if (err) { + console.info("Flush to file failed with err: " + err) + return + } + console.info("Flushed to file successfully.") + }) + ``` + + +### flush + +flush\(\): Promise + +Saves the modification of the current object to the current **Storage** instance and stores the modification to the file in an asynchronous mode. + +This method uses an asynchronous mode. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.flush() + promise.then(() => { + console.info("Flushed to file successfully.") + }).catch((err) => { + console.info("Flush to file failed with err: " + err) + }) + ``` + + +### clearSync + +clearSync\(\): void + +Clears all data in a storage object. + +This method uses a synchronous mode. + +- Example: + + ``` + storage.clearSync() + ``` + + +### clear + +clear\(callback: AsyncCallback\): void + +Clears all data in a storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.clear(function (err) { + if (err) { + console.info("Clear to file failed with err: " + err) + return + } + console.info("Cleared to file successfully.") + }) + ``` + + +### clear + +clear\(\): Promise + +Clears all data in a storage object. + +This method uses an asynchronous mode. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.clear() + promise.then(() => { + console.info("Cleared to file successfully.") + }).catch((err) => { + console.info("Clear to file failed with err: " + err) + }) + ``` + + +### on \('change'\) + +on\(type: 'change', callback: Callback\): void + +Subscribes to data changes. The **StorageObserver** needs to be implemented. When the value of the key subscribed to is changed, a callback will be invoked after **flush\(\)** or **flushSync\(\)** is executed. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

type

+

string

+

Event type. The value change indicates a data change event.

+

callback

+

Callback<StorageObserver>

+

Callback object.

+
+ +- Example: + + ``` + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + storage.on('change', observer) + storage.putSync('startup', 'auto') + storage.flushSync() // observer will be called. + ``` + + +### off \('change'\) + +off\(type: 'change', callback: Callback\): void + +Unsubscribes from data changes. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

type

+

string

+

Event type. The value change indicates a data change event.

+

callback

+

Callback<StorageObserver>

+

Callback object to be canceled.

+
+ +- Example: + + ``` + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + storage.off('change', observer) + ``` + + +## StorageObserver + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

No

+

Data changed

+
+ diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md new file mode 100644 index 0000000000000000000000000000000000000000..c3f2bb5356a8cd01126493fa92f345e2c1ef76f8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -0,0 +1,350 @@ +# Device Info + +## Modules to Import + +``` +import deviceInfo from '@ohos.deviceInfo' +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

deviceType

+

string

+

Yes

+

No

+

Device type.

+

manufacture

+

string

+

Yes

+

No

+

Device manufacturer.

+

brand

+

string

+

Yes

+

No

+

Device brand.

+

marketName

+

string

+

Yes

+

No

+

External product series.

+

productSeries

+

string

+

Yes

+

No

+

Product series.

+

productModel

+

string

+

Yes

+

No

+

Product model.

+

softwareModel

+

string

+

Yes

+

No

+

Software model.

+

hardwareModel

+

string

+

Yes

+

No

+

Hardware model.

+

hardwareProfile

+

string

+

Yes

+

No

+

Hardware profile.

+

serial

+

string

+

Yes

+

No

+

Device serial number.

+

bootloaderVersion

+

string

+

Yes

+

No

+

Bootloader version.

+

abiList

+

string

+

Yes

+

No

+

Application binary interface (Abi) list.

+

securityPatchTag

+

string

+

Yes

+

No

+

Security patch tag.

+

displayVersion

+

string

+

Yes

+

No

+

Product version.

+

incrementalVersion

+

string

+

Yes

+

No

+

Incremental version.

+

osReleaseType

+

string

+

Yes

+

No

+

Release type. The options are as follows:

+
  • Canary: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
  • Beta: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
  • Release: Official release open to all developers. This release promises that all APIs are stable.
+

osFullName

+

string

+

Yes

+

No

+

OS version.

+

majorVersion

+

number

+

Yes

+

No

+

Major version, incrementing along with OS version updates.

+

seniorVersion

+

number

+

Yes

+

No

+

Senior version, incrementing along with architecture and feature updates.

+

featureVersion

+

number

+

Yes

+

No

+

Feature version.

+

buildVersion

+

number

+

Yes

+

No

+

Build version.

+

sdkApiVersion

+

number

+

Yes

+

No

+

SDK API version.

+

firstApiVersion

+

number

+

Yes

+

No

+

First API version.

+

versionId

+

string

+

Yes

+

No

+

Version ID.

+

buildType

+

string

+

Yes

+

No

+

Build type.

+

buildUser

+

string

+

Yes

+

No

+

Build user.

+

buildHost

+

string

+

Yes

+

No

+

Build host.

+

buildTime

+

string

+

Yes

+

No

+

Build time.

+

buildRootHash

+

string

+

Yes

+

No

+

Build root hash.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..43e248fb82075971c2e32b7fa77003d9ddff5bf3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -0,0 +1,456 @@ +# Device Management + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import deviceManager from '@ohos.distributedHardware.deviceManager'; +``` + +## deviceManager.createDeviceManager + +createDeviceManager\(bundleName: string, callback: AsyncCallback\): void + +Creates a **DeviceManager** instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the application.

+

callback

+

AsyncCallback<DeviceManager>

+

Yes

+

Callback invoked to return the DeviceManager instance created.

+
+ +- Example + + ``` + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.info("createDeviceManager err:" + JSON.stringify(err)); + return; + } + console.info("createDeviceManager success"); + this.dmInstance = data; + }); + ``` + + +## DeviceStateChangeAction + +Enumerates the device states. + + + + + + + + + + + + + + + + + + + + + + + + +

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.

+
+ +## DeviceType + +Enumerates device types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SPEAKER

+

0x0A

+

Smart speaker.

+

PHONE

+

0x0E

+

Phone.

+

TABLET

+

0x11

+

Tablet.

+

WEARABLE

+

0x6D

+

Wearable.

+

TV

+

0x9C

+

Smart TV.

+
+ +## DeviceInfo + +Defines device information. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceId

+

number

+

Yes

+

Unique device identifier.

+

deviceName

+

string

+

Yes

+

Device name.

+

deviceType

+

number

+

Yes

+

Device type.

+
+ +## DeviceManager + +Creates a **DeviceManager** instance to obtain information about trusted devices and local devices. Before calling any method in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. + +### release + +release\(\): void + +Releases the **DeviceManager** instance that is no longer used. + +- Example + + ``` + dmInstance.release(); + ``` + + +### getTrustedDeviceListSync + +getTrustedDeviceListSync\(\): Array + +Obtains all trusted devices synchronously. + +- Return values + + + + + + + + + + +

Name

+

Description

+

Array<DeviceInfo>

+

List of trusted devices obtained.

+
+ +- Example + + ``` + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + ``` + + +### on\('deviceStateChange'\) + +on\(type: 'deviceStateChange', callback: Callback<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void + +Subscribes to changes in the device state. + +- 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, device: DeviceInfo }>

+

Yes

+

Callback invoked to return the device information and state.

+
+ + +- Example + + ``` + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); + } + ); + ``` + + +### off\('deviceStateChange'\) + +off\(type: 'deviceStateChange', callback?: Call back<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void + +Unsubscribes from changes in the device state. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Event type. The value deviceStateChange indicates an event of device state change.

+

callback

+

Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>

+

Yes

+

Callback used to return the device state changes.

+
+ + +- Example + + ``` + dmInstance.off('deviceStateChange', (data) => { + console.info('deviceStateChange' + JSON.stringify(data)); + } + ); + ``` + + +### on\('serviceDie'\) + +on\(type: 'serviceDie', callback: \(\) =\> void\): void + +Subscribes to dead events of the **DeviceManager** service. + +- 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.

+
+ + +- Example + + ``` + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + } + ); + ``` + + +### off\('serviceDie'\) + +off\(type: 'serviceDie', callback?: \(\) =\> void\): void + +Unsubscribes from dead events of the **DeviceManager** service. + +- 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.

+
+ + +- Example + + ``` + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + } + ); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md new file mode 100644 index 0000000000000000000000000000000000000000..5de72ecfb494dbcc6d192b30cff4d5cb290e1f67 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -0,0 +1,436 @@ +# Display + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import display from '@ohos.display'; +``` + +## Required Permissions + +None + +## DisplayState + +Provides the state of a display. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

STATE_UNKNOWN

+

0

+

Unknown.

+

STATE_OFF

+

1

+

The display is shut down.

+

STATE_ON

+

2

+

The display is powered on.

+

STATE_DOZE

+

3

+

The display is in sleep mode.

+

STATE_DOZE_SUSPEND

+

4

+

The display is in sleep mode, and the CPU is suspended.

+

STATE_VR

+

5

+

The display is in VR mode.

+

STATE_ON_SUSPEND

+

6

+

The display is powered on, and the CPU is suspended.

+
+ +## Display + +Describes the attributes of a display. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

id

+

number

+

Yes

+

No

+

ID of the display.

+

name

+

string

+

Yes

+

No

+

Name of the display.

+

alive

+

boolean

+

Yes

+

No

+

Whether the display is alive.

+

state

+

DisplayState

+

Yes

+

No

+

State of the display.

+

refreshRate

+

number

+

Yes

+

No

+

Refresh rate of the display.

+

rotation

+

number

+

Yes

+

No

+

Screen rotation angle of the display.

+

width

+

number

+

Yes

+

No

+

Width of the display, in pixels.

+

height

+

number

+

Yes

+

No

+

Height of the display, in pixels.

+

densityDPI

+

number

+

Yes

+

No

+

Screen density of the display, in DPI.

+

densityPixels

+

number

+

Yes

+

No

+

Screen density of the display, in pixels.

+

scaledDensity

+

number

+

Yes

+

No

+

Scaling factor for fonts displayed on the display.

+

xDPI

+

number

+

Yes

+

No

+

Exact physical dots per inch of the screen in the horizontal direction.

+

yDPI

+

number

+

Yes

+

No

+

Exact physical dots per inch of the screen in the vertical direction.

+
+ +## display.getDefaultDisplay + +getDefaultDisplay\(callback: AsyncCallback\): void; + +Obtains the default display object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Display>

+

Yes

+

Callback used to return the attributes of the default display.

+
+ +- Example + + ``` + var displayClass = null; + display.getDefaultDisplay((err, data) => { + if (err) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; + }); + ``` + + +## display.getAllDisplay + +getAllDisplay\(callback: AsyncCallback\>\): void; + +Obtains all the display objects. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Array<Display>>

+

Yes

+

Callback used to return the attributes of all displays.

+
+ +- Example + + ``` + display.getAllDisplay((err, data) => { + if (err) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)) + }); + ``` + + +## display.on\('add'|'remove'|'change'\) + +on\(type: 'add'|'remove'|'change', callback: Callback\): void; + +Enables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • add: listening for whether a display is added
  • remove: listening for whether a display is removed
  • change: listening for whether a display is changed
+

callback

+

Callback<number>

+

Yes

+

Callback used to return the ID of the display.

+
+ +- Example + + ``` + var type = "add"; + var callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)) + } + display.on(type, callback); + ``` + + +## display.off\('add'|'remove'|'change'\) + +off\(type: 'add'|'remove'|'change', callback?: Callback\): void; + +Disables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • add: listening for whether a display is added
  • remove: listening for whether a display is removed
  • change: listening for whether a display is changed
+

callback

+

Callback<number>

+

No

+

Callback used to return the ID of the display.

+
+ +- Example + + ``` + var type = "remove"; + display.off(type); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md new file mode 100644 index 0000000000000000000000000000000000000000..f0eaf4979b085d3376d35bec15450e998d879276 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -0,0 +1,300 @@ +# Distributed Account Management + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import account_distributedAccount from '@ohos.account.distributedAccount'; +``` + +## account\_distributedAccount.getDistributedAccountAbility + +getDistributedAccountAbility\(\): DistributedAccountAbility + +Obtains a **DistributedAccountAbility** instance. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DistributedAccountAbility

+

Instance that provides methods for querying and updating the login state of a distributed account.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + ``` + + +## DistributedAccountAbility + +Provides methods for querying and updating the login state of a distributed account. \(You must obtain a **DistributedAccountAbility** instance first.\) + +### queryOsAccountDistributedInfo + +queryOsAccountDistributedInfo\(callback: AsyncCallback\): void + +Obtains distributed account information. This method uses an asynchronous callback to return the result. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<DistributedInfo>

+

Yes

+

Callback invoked to return the distributed account information.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo((err, data) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + ``` + + +### queryOsAccountDistributedInfo + +queryOsAccountDistributedInfo\(\): Promise + +Obtains distributed account information. This method uses a promise to return the result asynchronously. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<DistributedInfo>

+

Promise used to return the result.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); + }); + ``` + + +### updateOsAccountDistributedInfo + +updateOsAccountDistributedInfo\(accountInfo: DistributedInfo, callback: AsyncCallback\): void + +Updates distributed account information. This method uses an asynchronous callback to return the result. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

accountInfo

+

DistributedInfo

+

Yes

+

Distributed account information.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked when the distributed account information is updated.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +### updateOsAccountDistributedInfo + +updateOsAccountDistributedInfo\(accountInfo: DistributedInfo\): Promise + +Updates distributed account information. This method uses a promise to return the result asynchronously. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

accountInfo

+

DistributedInfo

+

Yes

+

Distributed account information.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { + console.log('updateOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +## DistributedInfo + +Defines distributed OS account information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of a distributed account. It must be a non-null string.

+

id

+

string

+

Yes

+

UID of a distributed account. It must be a non-null string.

+

event

+

string

+

Yes

+

Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:

+
  • Ohos.account.event.LOGIN
  • Ohos.account.event.LOGOUT
  • Ohos.account.event.TOKEN_INVALID
  • Ohos.account.event.LOGOFF
+

scalableData

+

object

+

No

+

Extended information about a distributed account. Customized information is passed in key-value pairs.

+

Note: This parameter is reserved and not used in query and update methods.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md new file mode 100644 index 0000000000000000000000000000000000000000..00c4c58a74518ac30199dc98c66f275017fa25a6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -0,0 +1,1490 @@ +# Distributed Data Management + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import distributedData from '@ohos.data.distributedData'; +``` + +## Required Permissions + +None + +## distributedData.createKVManager + +createKVManager\(config: KVManagerConfig, callback: AsyncCallback\): void + +Creates a **KVManager** object to manage key-value \(KV\) stores. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

KVManagerConfig

+

Yes

+

Configuration of the KVManager object, including the bundle name and user information of the caller.

+

callback

+

AsyncCallback<KVManager>

+

Yes

+

Callback invoked to return the KVManager object created.

+
+ +- Example + + ``` + let kvManager; + try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : 0 + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("createKVManager err: " + JSON.stringify(err)); + return; + } + console.log("createKVManager success"); + kvManager = manager; + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +## distributedData.createKVManager + +createKVManager\(config: KVManagerConfig\): Promise + +Creates a **KVManager** object to manage KV stores. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

KVManagerConfig

+

Yes

+

Configuration of the KVManager object, including the bundle name and user information of the caller.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<KVManager>

+

Promise used to return the KVManager object created.

+
+ +- Example + + ``` + let kvManager; + try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : 0 + } + } + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("createKVManager success"); + kvManager = manager; + }).catch((err) => { + console.log("createKVManager err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +## KVManagerConfig + +Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

userInfo

+

UserInfo

+

Yes

+

User information.

+

bundleName

+

string

+

Yes

+

Bundle name.

+
+ +## UserInfo + +Defines user information. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

userId

+

string

+

Yes

+

User ID.

+

userType

+

UserType

+

Yes

+

User type.

+
+ +## UserType + +Defines the user type. + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SAME_USER_ID

+

0

+

User who logs in to different devices using the same account.

+
+ +## KVManager + +Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use **createKVManager** to create a **KVManager** object. + +### getKVStore + +getKVStore\(storeId: string, options: Options, callback: AsyncCallback\): void + +Creates and obtains a KV store. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

storeId

+

string

+

Yes

+

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

+

options

+

Options

+

Yes

+

Configuration of the KV store.

+

callback

+

AsyncCallback<T>,

+

<T extends KVStore>

+

Yes

+

Callback invoked to return the KV store created.

+
+ +- Example + + ``` + let kvStore; + try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : 1, + securityLevel : 3, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.log("getKVStore err: " + JSON.stringify(err)); + return; + } + console.log("getKVStore success"); + kvStore = store; + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### getKVStore + +getKVStore\(storeId: string, options: Options\): Promise + +Creates and obtains a KV store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

storeId

+

string

+

Yes

+

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

+

options

+

Options

+

Yes

+

Configuration of the KV store.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<T>

+

<T extends KVStore>

+

Promise used to return the KV store created.

+
+ +- Example + + ``` + let kvStore; + try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : 1, + securityLevel : 3, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("getKVStore success"); + kvStore = store; + }).catch((err) => { + console.log("getKVStore err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +## Options + +Provides KV store configuration. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

createIfMissing

+

boolean

+

No

+

Whether to create a KV store if no database file exists. By default, a KV store is created.

+

encrypt

+

boolean

+

No

+

Whether to encrypt database files. By default, database files are not encrypted.

+

backup

+

boolean

+

No

+

Whether to back up database files. By default, database files are backed up.

+

autoSync

+

boolean

+

No

+

Whether database files are automatically synchronized. By default, database files are not automatically synchronized.

+

kvStoreType

+

KVStoreType

+

No

+

Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.

+

securityLevel

+

SecurityLevel

+

No

+

Security level of the KV store. By default, the security level is not set.

+
+ +## KVStoreType + +Defines the KV store types. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DEVICE_COLLABORATION

+

0

+

Device KV store.

+

SINGLE_VERSION

+

1

+

Single KV store.

+

MULTI_VERSION

+

2

+

Multi-version KV store. This type is not supported currently.

+
+ +## SecurityLevel + +Defines the KV store security levels. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

NO_LEVEL

+

0

+

No security level is set for the KV store.

+

S0

+

1

+

The KV store security level is public.

+

S1

+

2

+

The KV store security level is low. If data leakage occurs, minor impact will be caused on the database.

+

S2

+

3

+

The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database.

+

S3

+

5

+

The KV store security level is high. If data leakage occurs, major impact will be caused on the database.

+

S4

+

6

+

The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database.

+
+ +## Constants + +Defines the KV store constants. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

MAX_KEY_LENGTH

+

1024

+

Maximum length (in bytes) of a key in the KV store.

+

MAX_VALUE_LENGTH

+

4194303

+

Maximum length (in bytes) of a value in the KV store.

+

MAX_KEY_LENGTH_DEVICE

+

896

+

Maximum length of the device coordinate key.

+

MAX_STORE_ID_LENGTH

+

128

+

Maximum length (in bytes) of the KV store ID.

+

MAX_QUERY_LENGTH

+

512000

+

Maximum query length.

+

MAX_BATCH_SIZE

+

128

+

Maximum size of a batch operation.

+
+ +## KVStore + +Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use **getKVStore** to create a **KVStore** object. + +### put + +put\(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback\): void + +Adds a key-value pair of the specified type to the KV store. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Value of the key-value pair to add. The value type can be Uint8Array, number, string, or boolean.

+

A value of the Uint8Array or string type cannot exceed MAX_VALUE_LENGTH.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### put + +put\(key: string, value: Uint8Array | string | number | boolean\): Promise + +Adds a key-value pair of the specified type to the KV store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Value of the key-value pair to add. The value type can be Uint8Array, number, string, or boolean.

+

A value of the Uint8Array or string type cannot exceed MAX_VALUE_LENGTH.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ + +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### delete + +delete\(key: string, callback: AsyncCallback\): void + +Deletes a KV pair from the KV store. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the KV pair to delete. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("delete err: " + JSON.stringify(err)); + return; + } + console.log("delete success"); + }); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### delete + +delete\(key: string\): Promise + +Deletes a KV pair from the KV store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the KV pair to delete. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("delete success"); + }).catch((err) => { + console.log("delete err: " + JSON.stringify(err)); + }); + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### on + +on\(event: 'dataChange', type: SubscribeType, observer: Callback\): void + +Subscribes to data changes of the specified type. This method uses a synchronization callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

event

+

'dataChange'

+

Type of the events.

+

type

+

SubscribeType

+

Type of data changes.

+

observer

+

Callback<ChangeNotification>

+

Callback invoked to return the result.

+
+ +- Example + + ``` + kvStore.on('dataChange', 2, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); + }); + ``` + + +### on + +on\(event: 'syncComplete', syncCallback: Callback\>\): void + +Subscribes to notifications of data synchronization completion. This method uses a synchronization callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

event

+

'syncComplete'

+

Type of the events.

+

syncCallback

+

Callback<Array<[string, number]>>

+

Callback invoked to return the result.

+
+ +- Example + + ``` + kvStore.on('syncComplete', function (data) { + console.log("syncComplete callback call data: " + data); + }); + ``` + + +## SubscribeType + +Defines the subscription type. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SUBSCRIBE_TYPE_LOCAL

+

0

+

Local data changes.

+

SUBSCRIBE_TYPE_REMOTE

+

1

+

Peer data changes.

+

SUBSCRIBE_TYPE_ALL

+

2

+

Local and peer data changes.

+
+ +## ChangeNotification + +Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

insertEntries

+

Entry[]

+

Yes

+

Yes

+

Data inserted.

+

updateEntries

+

Entry[]

+

Yes

+

Yes

+

Data updated.

+

deleteEntries

+

Entry[]

+

Yes

+

Yes

+

Data deleted.

+

deviceId

+

string

+

Yes

+

Yes

+

UUID of the device.

+
+ +## Entry + +Defines the key-value pairs stored in the database. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

key

+

string

+

Yes

+

Yes

+

Key of the key-value pair stored in the database.

+

value

+

Value

+

Yes

+

Yes

+

Value of the key-value pair stored in the database.

+
+ +## Value + +Defines the value in a key-value pair. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

ValueType

+

Yes

+

Yes

+

Type of the value.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Yes

+

Specific value. A value of the Uint8Array or string type cannot exceed MAX_VALUE_LENGTH.

+
+ +## ValueType + +Defines the types of the value in a key-value pair. + +It can be used only by internal applications. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

STRING

+

0

+

String.

+

INTEGER

+

1

+

Integer.

+

FLOAT

+

2

+

Float (single-precision floating point).

+

BYTE_ARRAY

+

3

+

Byte array.

+

BOOLEAN

+

4

+

Boolean.

+

DOUBLE

+

5

+

Double (double-precision floating point).

+
+ +## SingleKVStore + +Provides methods to query and synchronize data in a single KV store. This class inherits from **KVStore**. Before calling any method in **SingleKVStore**, you must use **getKVStore** to create a **KVStore** object. + +### get + +get\(key: string, callback: AsyncCallback\): void + +Obtains the value of a specified key. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the value to obtain. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

callback

+

AsyncCallback<Uint8Array | string | boolean | number>

+

Yes

+

Callback invoked to return the value obtained.

+
+ +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { + console.log("get success data: " + data); + }); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### get + +get\(key: string\): Promise + +Obtains the value of a specified key. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the value to obtain. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array | string | boolean | number>

+

Promise used to return the result.

+
+ + +- Example + + ``` + const KEY_TEST_STRING_ELEMENT = 'key_test_string'; + const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; + try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("get success data: " + data); + }).catch((err) => { + console.log("get err: " + JSON.stringify(err)); + }); + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); + }catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +### sync + +sync\(deviceIdList: string\[\], mode: SyncMode, allowedDelayMs?: number\): void + +Triggers synchronization of the KV store, which is in manual synchronization mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceIdList

+

string[]

+

Yes

+

List of IDs of the devices in the same networking environment to be synchronized.

+

mode

+

SyncMode

+

Yes

+

Synchronization mode.

+

allowedDelayMs

+

number

+

No

+

Allowed delay time, in ms.

+
+ +- Example + + ``` + kvStore.sync(deviceIds, 1, 1000); + ``` + + +## SyncMode + +Defines the synchronization mode. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

PULL_ONLY

+

0

+

Pull data from the peer end to the local end only.

+

PUSH_ONLY

+

1

+

Push data from the local end to the peer end only.

+

PUSH_PULL

+

2

+

Push data from the local end to the peer end and then pull data from the peer end to the local end.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md new file mode 100644 index 0000000000000000000000000000000000000000..2b6aa580963fbac78fa9b2676edfc46147593b70 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -0,0 +1,2051 @@ +# File Management + +>![](../../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. + +## Modules to Import + +``` +import fileio from '@ohos.fileio'; +``` + +## Required Permissions + +None + +## Usage + +Before using this module to perform operations on a file or directory, you must obtain the absolute path of the file or directory. For details, see **getOrCreateLocalDir** in the **Context** module. + + +Absolute file or directory path = Application directory path + File name or directory name + +For example, if the application directory obtained by using the API is _dir_ and the file name is _file name_**.txt**, the absolute path of the file is as follows: + +``` +let path = dir + "file name.txt" +``` + +The file descriptor is as follows: + +``` +let fd = fileio.openSync(path); +``` + +## fileio.statSync + +statSync\(path:string\): Stat + +Synchronously obtains file information. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Stat

+

Detailed file information.

+
+ +- Example + + ``` + let stat = fileio.statSync(path); + ``` + + +## fileio.opendirSync + +opendirSync\(path: string\): Dir + +Synchronously opens a directory. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to open.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Dir

+

An instance of the Dir class corresponding to a directory.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(path); + ``` + + +## fileio.accessSync + +accessSync\(path: string, mode?: number\): void + +Synchronously checks whether the current process can access a file. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

number

+

No

+

Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is 0.

+

The options are as follows:

+
  • 0: Check whether the file exists.
+
  • 1: Check whether the current process has the execute permission on the file.
  • 2: Check whether the current process has the write permission on the file.
  • 4: Check whether the process has the read permission on the file.
+
+ +- Example + + ``` + fileio.accessSync(path); + ``` + + +## fileio.closeSync + +closeSync\(fd: number\): void + +Synchronously closes a file. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to close.

+
+ +- Example + + ``` + fileio.closeSync(fd); + ``` + + +## fileio.copyFileSync + +fileio.copyFileSync\(src: string, dest: string, mode?:number\): void + +Synchronously copies a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

src

+

string

+

Yes

+

Path of the file to copy.

+

dest

+

string

+

Yes

+

Target file path.

+

mode

+

number

+

No

+

Option for overwriting the file of the same name in the destination path. The default value is 0, which is the only value supported.

+

0: Overwrite the file with the same name completely and truncate the part that is not overwritten.

+
+ +- Example + + ``` + fileio.copyFileSync(src, dest); + ``` + + +## fileio.mkdirSync + +fileio.mkdirSync\(path: string, mode?: number\): void + +Synchronously creates a directory. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to create.

+

mode

+

number

+

No

+

Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is 0o775.

+
  • 0o775: The owner has the read, write, and execute permissions, and other users have the read and execute permissions on the directory.
  • 0o700: The owner has the read, write, and execute permissions on the directory.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.mkdirSync(path); + ``` + + +## fileio.openSync + +openSync\(path: string, flags?: number, mode?: number\): number + +Synchronously opens a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to open.

+

flags

+

number

+

No

+

Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.

+
  • 0o0: Open file in read-only mode.
  • 0o1: Open file in write-only mode.
  • 0o2: Open file in read/write mode.
+

In addition, you can specify the following options using a bitwise OR operator (|). By default, no additional option is specified.

+
  • 0o100: If the file does not exist, create a file. If you use this option, you must also specify mode.
  • 0o200: If 0o100 is added and the file already exists, throw an exception.
  • 0o1000: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
  • 0o2000: Open the file in append mode. New data will be appended to the file (written to the end of the file).
  • 0o4000: If path points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
  • 0o200000: If path points to a directory, throw an exception.
  • 0o400000: If path points to a symbolic link, throw an exception.
  • 0o4010000: Open the file in synchronous I/O mode.
+

mode

+

number

+

No

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is 0o666.

+
  • 0o666: The owner, user group, and other users have the read and write permissions on the file.
  • 0o700: The owner has the read, write, and execute permissions on the file.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: All user groups have the read, write, and execute permissions on the directory.
  • 0o040: All user groups have the read permission on the directory.
  • 0o020: All user groups have the write permission on the directory.
  • 0o010: All user groups have the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

File descriptor of the file opened.

+
+ +- Example + + ``` + fileio.openSync(path); + ``` + + +## fileio.readSync + +readSync\(fd: number, buffer: ArrayBuffer, options?: Object\): number + +Synchronously reads data from a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to read.

+

buffer

+

ArrayBuffer

+

Yes

+

Buffer used for reading the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the buffer to which the data will be read in reference to the start address of the buffer. It is optional. The default value is 0.
  • length (number): length of the data to read. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to read in the file. It is optional. By default, data is read from the current position.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data read.

+
+ +- Example + + ``` + let fd = fileio.openSync(path, 0o2); + let buf = new ArrayBuffer(4096); + fileio.readSync(fd, buf); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + ``` + + +## fileio.rmdirSync + +rmdirSync\(path: string\): void + +Synchronously removes a directory. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to remove.

+
+ +- Example + + ``` + fileio.rmdirSync(path); + ``` + + +## fileio.unlinkSync + +unlinkSync\(path: string\): void + +Synchronously deletes a file. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to delete.

+
+ +- Example + + ``` + fileio.unlinkSync(path); + ``` + + +## fileio.writeSync + +writeSync\(fd: number, buffer: ArrayBuffer | string, options?:Object\): number + +Synchronously writes data to a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to write.

+

buffer

+

ArrayBuffer | string

+

Yes

+

A string or data from a buffer to be written to the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the data to write in reference to the start address of the data. It is optional. The default value is 0.
  • length (number): length of the data to write. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to be written in the file. It is optional. By default, data is written from the current position.
  • encoding (string): format of the data to be encoded. You must set it when the data is a string. The default value is utf-8. Only utf-8 is supported.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data written in the file.

+
+ +- Example + + ``` + let fd = fileio.openSync(path, 0o102, 0o666); + fileio.writeSync(fd, "hello, world"); + ``` + + +## fileio.chmodSync7+ + +chmodSync\(path: string, mode: number\): void + +Synchronously changes the file permissions based on its path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

number

+

Yes

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).

+
  • 0o700: The owner has the read, write, and execute permissions on the directory.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.chmodSync(fpath, mode); + ``` + + +## fileio.fstatSync7+ + +fstatSync\(fd: number\): Stat + +Synchronously obtains file status information based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Stat>

+

File status information obtained.

+
+ + +- Example + + ``` + let fd = fileio.openSync(path); + let stat = fileio.fstatSync(fd); + ``` + + +## fileio.ftruncateSync7+ + +ftruncateSync\(fd: number, len?: number\): void + +Synchronously truncates a file based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to truncate.

+

len

+

number

+

No

+

File length, in bytes, after truncation.

+
+ + +- Example + + ``` + fileio.ftruncate(fd, len); + ``` + + +## fileio.fchmodSync7+ + +fchmodSync\(existingPath: string, newPath: string\): void + +Synchronously changes the file permissions based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

mode

+

number

+

Yes

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).

+
  • 0o700: The owner has the read, write, and execute permissions on the file.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.fchmodSync(fd, mode); + ``` + + +## fileio.truncateSync7+ + +truncateSync\(fpath: string, len?: number\): void + +Synchronously truncates a file based on the file path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to truncate.

+

len

+

number

+

No

+

File length, in bytes, after truncation.

+
+ + +- Example + + ``` + fileio.ftruncate(path, len); + ``` + + +## fileio.renameSync7+ + +renameSync\(oldPath: string, newPath: string\): void + +Synchronously renames a file. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

oldPath

+

string

+

Yes

+

Absolute path of the file to rename.

+

Newpath

+

String

+

Yes

+

Absolute path of the file renamed.

+
+ +- Example + + ``` + fileio.renameSync(oldpath, newpath); + ``` + + +## fileio.fsyncSync7+ + +fsyncSync\(fd: number\): void + +Synchronizes a file in synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to synchronize.

+
+ +- Example + + ``` + fileio.fyncsSync)(fd); + ``` + + +## fileio.chownSync7+ + +chownSync\(path: string, uid: number, gid: number\): void + +Synchronously changes the file owner based on its path. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

uid

+

number

+

Yes

+

New UID.

+

gid

+

number

+

Yes

+

New GID.

+
+ +- Example + + ``` + let stat = fileio.statSync(fpath) + fileio.chownSync(path, stat.uid, stat.gid); + ``` + + +## fileio.createStreamSync7+ + +createStreamSync\(path: string, mode: string\): Stream + +Synchronously opens a stream based on the file path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

string

+

Yes

+
  • r: Open a file for reading. The file must exist.
  • r+: Open a file for both reading and writing. The file must exist.
  • w: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
  • w+: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
  • a: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
  • a+: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
+
+ + +- Return values + + + + + + + + + + +

Name

+

Description

+

Stream

+

Stream operation result.

+
+ +- Example + + ``` + let ss = fileio.createStream(path, "r+"); + ``` + + +## fileio.fdopenStreamSync7+ + +fdopenStreamSync\(fd: number, mode: string\): Stream + +Synchronously opens a stream based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

mode

+

string

+

Yes

+
  • r: Open a file for reading. The file must exist.
  • r+: Open a file for both reading and writing. The file must exist.
  • w: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
  • w+: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
  • a: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
  • a+: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
+
+ + +- Return values + + + + + + + + + + +

Name

+

Description

+

Stream

+

Stream operation result.

+
+ +- Example + + ``` + let ss = fileio.fdopenStreamSync(fd, "r+"); + ``` + + +## fileio.fchownSync7+ + +fchownSync\(fd: number, uid: number, gid: number\): void + +Synchronously changes the file owner based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

uid

+

number

+

Yes

+

New UID.

+

gid

+

number

+

Yes

+

New GID.

+
+ +- Example + + ``` + let stat = fileio.statSync(fpath); + fileio.fchownSync(fd, stat.uid, stat.gid); + ``` + + +## Stat + +Provides detailed file information. Before invoking a method of the **Stat** class, use the [fileio.statSync](#section014281412198) method to create a **Stat** instance. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

dev

+

number

+

Yes

+

No

+

Major device number.

+

ino

+

number

+

Yes

+

No

+

File ID. Different files on the same device have different inos.

+

mode

+

number

+

Yes

+

No

+

File type and permission. The first four bits indicate the file type, and the last 12 bits indicate the permission. The bit fields are described follows:

+
  • 0o170000: mask used to obtain the file type.
  • 0o140000: The file is a socket.
  • 0o120000: The file is a symbolic link.
  • 0o100000: The file is a regular file.
  • 0o060000: The file is a block device.
  • 0o040000: The file is a directory.
  • 0o020000: The file is a character device.
  • 0o010000: The file is a named pipe (also known as a FIFO).
  • 0o0700: mask used to obtain owner permissions.
  • 0o0400: The owner has the read permission on a regular file or a directory entry.
  • 0o0200: The owner has the permission to write a regular file or has the permission to create and delete a directory entry.
  • 0o0100: The owner has the permission to execute a regular file or has the permission to search for the specified path in a directory.
  • 0o0070: mask used to obtain user group permissions.
  • 0o0040: The user group has the read permission on a regular file or a directory entry.
  • 0o0020: The user group has the permission to write a regular file or has the permission to create and delete a directory entry.
  • 0o0010: The user group has the permission to execute a regular file or has the permission to search for the specified path in a directory.
  • 0o0007: mask used to obtain permissions of other users.
  • 0o0004: Other user groups have the read permission on a regular file or a directory entry.
  • 0o0002: Other user groups have the permission to write a regular file or have the permission to create and delete a directory entry.
  • 0o0001: Other user groups have the permission to execute a regular file or have the permission to search for the specified path in a directory.
+

nlink

+

number

+

Yes

+

No

+

Number of hard links in the file.

+

uid

+

number

+

Yes

+

No

+

ID of the file owner.

+

gid

+

number

+

Yes

+

No

+

ID of the user group of the file.

+

rdev

+

number

+

Yes

+

No

+

Minor device number.

+

size

+

number

+

Yes

+

No

+

File size, in bytes. This parameter is valid only for regular files.

+

blocks

+

number

+

Yes

+

No

+

Number of blocks occupied by a file. Each block is 512 bytes.

+

atime

+

number

+

Yes

+

No

+

Time of the last access of file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+

mtime

+

number

+

Yes

+

No

+

Time of the last modification of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+

ctime

+

number

+

Yes

+

No

+

Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+
+ +### isBlockDevice + +isBlockDevice\(\): boolean + +Checks whether a directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a block special file.

+
+ +- Example + + ``` + let isBLockDevice = fileio.statSync(path).isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice\(\): boolean + +Checks whether a directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a character special file.

+
+ +- Example + + ``` + let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory\(\): boolean + +Checks whether a directory entry is a directory. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a directory.

+
+ +- Example + + ``` + let isDirectory= fileio.statSync(path).isDirectory(); + ``` + + +### isFIFO + +isFIFO\(\): boolean + +Checks whether a directory entry is a named pipe \(or FIFO\). Named pipes are used for inter-process communication. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a FIFO.

+
+ +- Example + + ``` + let isFIFO= fileio.statSync(path).isFIFO(); + ``` + + +### isFile + +isFile\(\): boolean + +Checks whether a directory entry is a regular file. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a regular file.

+
+ +- Example + + ``` + let isFile= fileio.statSync(fpath).isFile(); + ``` + + +### isSocket + +isSocket\(\): boolean + +Checks whether a directory entry is a socket. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a socket.

+
+ +- Example + + ``` + let isSocket = fileio.statSync(path).isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink\(\): boolean + +Checks whether a directory entry is a symbolic link. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a symbolic link.

+
+ +- Example + + ``` + let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); + ``` + + +## Stream7+ + +File stream. Before calling a method of the **Stream** class, use the [fileio.createStreamSync](#section1956102153713) method to create a **Stream** instance. + +### closeSync7+ + +closeSync\(\): void + +Synchronously closes the stream. + +- Example + + ``` + let ss= fileio.createStreamSync(path); + ss.closeSync(); + ``` + + +### flushSync7+ + +flushSync\(\): void + +Synchronously flushes the stream. + +- Example + + ``` + let ss= fileio.createStreamSync(path); + ss.flushSync(); + ``` + + +### writeSync7+ + +writeSync\(buffer: ArrayBuffer | string, options?:Object\): number + +Synchronously writes data into the stream. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer | string

+

Yes

+

A string or data from a buffer to be written to the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the data to write in reference to the start address of the data. It is optional. The default value is 0.
  • length (number): length of the data to write. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to be written in the file. It is optional. By default, data is written from the current position.
  • encoding (string): format of the data to be encoded. You must set it when the data is a string. The default value is utf-8. Only utf-8 is supported.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data written in the file.

+
+ +- Example + + ``` + let ss= fileio.createStreamSync(fpath,"r+"); + ss.writeSync("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}); + ``` + + +### readSync7+ + +readSync\(buffer: ArrayBuffer, options?: Object\): number + +Synchronously reads data from the stream. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer

+

Yes

+

Buffer used for reading the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the buffer to which the data will be read in reference to the start address of the buffer. It is optional. The default value is 0.
  • length (number): length of the data to read. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to read in the file. It is optional. By default, data is read from the current position.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data read.

+
+ +- Example + + ``` + let ss = fileio.createStreamSync(fpath, "r+"); + ss.readSync(new ArrayBuffer(4096),{offset: 1,length: FILE_CONTENT.length,position: 5}); + ``` + + +## Dir + +Manages directories. Before calling a method of the **Dir** class, use the [fileio.opendirSync](#section7741145112216) method to create a **Dir** instance. + +### readSync + +readSync\(\): Dirent + +Synchronously reads the next directory entry. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Dirent

+

Directory entry read.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let dirent = dir.readSync(); + console.log(dirent.name); + ``` + + +### closeSync + +closeSync\(\): void + +Closes a directory. After a directory is closed, the file descriptor in **Dir** will be released and the directory entry cannot be read from **Dir**. + +- Example + + ``` + let dir = fileio.opendirSync(dpath); + dir.closeSync(); + ``` + + +## Dirent + +Provides information about files and directories. Before calling a method of the **Dirent** class, use the [readSync](#section10198204912710) method to create a **Dirent** instance. + +### Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

name

+

string

+

Yes

+

No

+

Directory entry name.

+
+ +### isBlockDevice + +isBlockDevice\(\): boolean + +Checks whether a directory entry is a block device file. A block special file supports access by block only, and it is cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a block device file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isBLockDevice = dir.readSync().isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice\(\): boolean + +Checks whether a directory entry is a character device file. A character special file supports random access, and it is not cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a character device file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isCharacterDevice = dir.readSync().isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory\(\): boolean + +Checks whether a directory entry is a directory. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a directory.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isDirectory = dir.readSync().isDirectory(); + ``` + + +### isFIFO + +isFIFO\(\): boolean + +Checks whether a directory entry is a named pipe \(or FIFO\). Named pipes are used for inter-process communication. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a FIFO.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isFIFO = dir.readSync().isFIFO(); + ``` + + +### isFile + +isFile\(\): boolean + +Checks whether a directory entry is a regular file. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a regular file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isFile = dir.readSync().isFile(); + ``` + + +### isSocket + +isSocket\(\): boolean + +Checks whether a directory entry is a socket. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a socket.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isSocket = dir.readSync().isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink\(\): boolean + +Checks whether a directory entry is a symbolic link. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a symbolic link.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isSymbolicLink = dir.readSync().isSymbolicLink(); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md new file mode 100644 index 0000000000000000000000000000000000000000..cc9dad8a12182393f6bafe668d9633210a2829ad --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -0,0 +1,418 @@ +# HiAppEvent + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import hiAppEvent from '@ohos.hiAppEvent'; +``` + +## Required Permissions + +None. + +## hiAppEvent.write + +write\(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback\): void + +Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

eventName

+

string

+

Yes

+

Indicates the application event name.

+

eventType

+

EventType

+

Yes

+

Indicates the application event type.

+

keyValues

+

object

+

Yes

+

Indicates an array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

+

callback

+

AsyncCallback<void>

+

No

+

Indicates the callback function, which can be used to process the received return value.

+
  • Value 0 indicates that the event verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value smaller than 0 indicates that the event verification fails, and the event will not be written to the event file.
+
+ +- Example + + ``` + hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { + if (err) { + // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Event writing succeeded. + console.log(`success to write event: ${value}`); + }); + ``` + + +## hiAppEvent.write + +write\(eventName: string, eventType: EventType, keyValues: object\): Promise + +Writes event information to the event file of the current day. This function supports JSON parameters and uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

eventName

+

string

+

Yes

+

Indicates the application event name.

+

eventType

+

EventType

+

Yes

+

Indicates the application event type.

+

keyValues

+

object

+

Yes

+

Indicates an array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed.

+
+ +- Example + + ``` + hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) + .then((value) => { + // Event writing succeeded. + console.log(`success to write event: ${value}`); + }).catch((err) => { + // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + }); + ``` + + +## hiAppEvent.configure + +configure\(config: ConfigOption\): boolean + +Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

ConfigOption

+

Yes

+

Configuration items for application event logging.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the configuration is successful; returns false otherwise.

+
+ +- Example + + ``` + // Configure the application event logging switch. + hiAppEvent.configure({ + disable: true + }); + + // Configure the maximum size of the directory that stores the event logging files. + hiAppEvent.configure({ + maxStorage: '100M' + }); + ``` + + +## ConfigOption + +Provides the configuration items for application event logging. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

disable

+

boolean

+

No

+

Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.

+

maxStorage

+

string

+

No

+

Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.

+
+ +## EventType + +Enumerates event types. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

FAULT

+

1

+

Fault event

+

STATISTIC

+

2

+

Statistical event

+

SECURITY

+

3

+

Security event

+

BEHAVIOR

+

4

+

Behavior event

+
+ +## Event + +Provides constants that define the names of all predefined events. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

USER_LOGIN

+

string

+

Yes

+

No

+

User login event.

+

USER_LOGOUT

+

string

+

Yes

+

No

+

User logout event.

+

DISTRIBUTED_SERVICE_START

+

string

+

Yes

+

No

+

Distributed service startup event.

+
+ +## Param + +Provides constants that define the names of all predefined event parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

USER_ID

+

string

+

Yes

+

No

+

Custom user ID.

+

DISTRIBUTED_SERVICE_NAME

+

string

+

Yes

+

No

+

Distributed service name.

+

DISTRIBUTED_SERVICE_INSTANCE_ID

+

string

+

Yes

+

No

+

Distributed service instance ID.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md new file mode 100644 index 0000000000000000000000000000000000000000..6f684c8c06d674c9cc43cc409acd1c2e962129f7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -0,0 +1,255 @@ +# Internationalization \(i18n\) + +>![](../../public_sys-resources/icon-note.gif) **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. +>- This module contains enhanced i18n APIs, which are not defined in ECMA 402. + + +## Modules to Import + +``` +import i18n from '@ohos.i18n'; +``` + +## Required Permissions + +None + +## i18n.getDisplayLanguage + +getDisplayLanguage\(language: string, locale: string, sentenceCase?: boolean\): string + +Obtains the localized script for the specified language. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

language

+

string

+

Yes

+

Specified language.

+

locale

+

string

+

Yes

+

Locale ID.

+

sentenceCase

+

boolean

+

No

+

Whether to use sentence case for the localized script.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Localized script for the specified language.

+
+ +- Example + + ``` + i18n.getDisplayLanguage("zh", "en-GB", true); + i18n.getDisplayLanguage("zh", "en-GB"); + ``` + + +## i18n.getDisplayCountry + +getDisplayCountry\(country: string, locale: string, sentenceCase?: boolean\): string + +Obtains the localized script for the specified country. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

country

+

string

+

Yes

+

Specified country.

+

locale

+

string

+

Yes

+

Locale ID.

+

sentenceCase

+

boolean

+

No

+

Whether to use sentence case for the localized script.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Localized script for the specified country.

+
+ +- Example + + ``` + i18n.getDisplayCountry("zh-CN", "en-GB", true); + i18n.getDisplayCountry("zh-CN", "en-GB"); + ``` + + +## i18n.getSystemLanguage + +getSystemLanguage\(\): string + +Obtains the system language. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System language ID.

+
+ +- Example + + ``` + i18n.getSystemLanguage(); + ``` + + +## i18n.getSystemRegion + +getSystemRegion\(\): string + +Obtains the system region. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System region ID.

+
+ +- Example + + ``` + i18n.getSystemRegion(); + ``` + + +## i18n.getSystemLocale + +getSystemLocale\(\): string + +Obtains the system locale. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System locale ID.

+
+ +- Example + + ``` + i18n.getSystemLocale(); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md new file mode 100644 index 0000000000000000000000000000000000000000..7d182fd07eb55b848088f153625278a4e469e405 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -0,0 +1,1180 @@ +# Internationalization \(intl\) + +>![](../../public_sys-resources/icon-note.gif) **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. +>- This module contains standard i18n APIs, which are defined in ECMA 402. + + +## Modules to Import + +``` +import Intl from '@ohos.intl'; +``` + +## Required Permissions + +None + +## Locale + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

language

+

string

+

Yes

+

No

+

Language associated with the locale.

+

script

+

string

+

Yes

+

No

+

Script type of the language.

+

region

+

string

+

Yes

+

No

+

Region associated with the locale.

+

baseName

+

string

+

Yes

+

No

+

Basic information about the locale.

+

caseFirst

+

string

+

Yes

+

No

+

Whether case is taken into account for the locale's collation rules.

+

calendar

+

string

+

Yes

+

No

+

Calendar for the locale.

+

collation

+

string

+

Yes

+

No

+

Collation rules for the locale.

+

hourCycle

+

string

+

Yes

+

No

+

Time system for the locale.

+

numberingSystem

+

string

+

Yes

+

No

+

Numbering system for the locale.

+

numeric

+

boolean

+

Yes

+

No

+

Whether to apply special collation rules for numeric characters.

+
+ +### constructor + +constructor\(locale: string, options?:options\) + +Creates a **Locale** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

options

+

No

+

Options for creating the Locale object.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + ``` + + +### toString + +toString\(\): string + +Converts locale information to a string. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

String containing locale information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.toString(); + ``` + + +### maximize + +maximize\(\): Locale + +Maximizes information of the **Locale** object. If the script and locale information is missing, add the information. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Locale

+

Locale object with the maximized information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.maximize(); + ``` + + +### minimize + +minimize\(\): Locale + +Minimizes information of the **Locale** object. If the script and locale information is present, delete the information. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Locale

+

Locale object with the minimized information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.minimize(); + ``` + + +## DateTimeFormat + +### constructor + +constructor\(locale: string, options?:DateTimeOptions\) + +Creates a **DateTimeOptions** object for the specified locale. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

DateTimeOptions

+

No

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ``` + + +### constructor + +constructor\(locales: Array, options?:DateTimeOptions\) + +Creates a **DateTimeOptions** object for the specified array of locales. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locales

+

Array<string>

+

Yes

+

An array of strings containing locale information.

+

options

+

DateTimeOptions

+

No

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ``` + + +### format + +format\(date: Date\): string; + +Formats the specified date and time. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Date and time to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

A string containing the formatted date and time.

+
+ + +- Example + + ``` + var date = new Date(2021, 11, 17, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.format(date); + ``` + + +### formatRange + +formatRange\(fromDate: Date, toDate: Date\): string; + +Formats the specified date range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

startDate

+

Date

+

Yes

+

Start date and time to be formatted.

+

endDate

+

Date

+

Yes

+

End date and time to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

A string containing the formatted date and time range.

+
+ + +- Example + + ``` + var startDate = new Date(2021, 11, 17, 3, 24, 0); + var endDate = new Date(2021, 11, 18, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.formatRange(startDate, endDate); + ``` + + +### resolvedOptions + +resolvedOptions\(\): DateTimeOptions + +Obtains the options of the **DateTimeFormat** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DateTimeOptions

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.resolvedOptions(); + ``` + + +## NumberFormat + +### constructor + +constructor\(locale: string, options?:NumberOptions\) + +Creates a **NumberFormat** object for the specified locale. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

NumberOptions

+

No

+

Options of the NumberFormat object.

+
+ +- Example + + ``` + var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ``` + + +### constructor + +constructor\(locales: Array, options?:NumberOptions\) + +Creates a **NumberFormat** object for the specified array of locales. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locales

+

Array<string>

+

Yes

+

An array of strings containing locale information.

+

options

+

NumberOptions

+

No

+

Options of the NumberFormat object.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + ``` + + +### format + +format\(number: number\): string; + +Formats a number. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

number

+

number

+

Yes

+

Number to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Formatted number.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + numfmt.format(1223); + ``` + + +### resolvedOptions + +resolvedOptions\(\): NumberOptions + +Obtains the options of the **NumberFormat** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

NumberOptions

+

Options of the NumberFormat object.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + numfmt.resolvedOptions(); + ``` + + +## DateTimeOptions + +Provides the options for the **DateTimeFormat** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

No

+

Locale information.

+

dateStyle

+

string

+

Yes

+

Yes

+

Date display format. The value can be long, short, medium, or full.

+

timeStyle

+

string

+

Yes

+

Yes

+

Time display format. The value can be long, short, medium, or full.

+

hourCycle

+

string

+

Yes

+

Yes

+

Hour cycle. The value can be h11, h12, h23, or h24.

+

timeZone

+

string

+

Yes

+

Yes

+

Time zone represented by a valid IANA time zone ID.

+

numberingSystem

+

string

+

Yes

+

Yes

+

Numbering system.

+

hour12

+

boolean

+

Yes

+

Yes

+

Whether to use the 12-hour clock.

+

weekday

+

string

+

Yes

+

Yes

+

Workday display format. The value can be long, short, or narrow.

+

era

+

string

+

Yes

+

Yes

+

Era display format. The value can be long, short, or narrow.

+

year

+

string

+

Yes

+

Yes

+

Year display format. The value can be numeric or 2-digit.

+

month

+

string

+

Yes

+

Yes

+

Month display format. The value can be numeric, 2-digit, long, short, or narrow.

+

day

+

string

+

Yes

+

Yes

+

Day display format. The value can be numeric or 2-digit.

+

hour

+

string

+

Yes

+

Yes

+

Hour display format. The value can be numeric or 2-digit.

+

minute

+

string

+

Yes

+

Yes

+

Minute display format. The value can be numeric or 2-digit.

+

second

+

string

+

Yes

+

Yes

+

Second display format. The value can be numeric or 2-digit.

+

timeZoneName

+

string

+

Yes

+

Yes

+

Localized representation of a time zone name.

+

dayPeriod

+

string

+

Yes

+

Yes

+

Time period display format. The value can be long, short, or narrow.

+

localeMatcher

+

string

+

Yes

+

Yes

+

Locale matching algorithm. The value can be lookup or best fit.

+

formatMatcher

+

string

+

Yes

+

Yes

+

Format matching algorithm. The value can be basic or best fit.

+
+ +## NumberOptions + +Provides the device capability. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

No

+

Locale information.

+

currency

+

string

+

Yes

+

Yes

+

Currency for the specified locale.

+

currencySign

+

string

+

Yes

+

Yes

+

Currency symbol.

+

currencyDisplay

+

string

+

Yes

+

Yes

+

Currency display mode. The value can be symbol, narrowSymbol, code, or name.

+

unit

+

string

+

Yes

+

Yes

+

Currency unit.

+

unitDisplay

+

string

+

Yes

+

Yes

+

Currency unit display format. The value can be long, short, or medium.

+

signDisplay

+

string

+

Yes

+

Yes

+

Number sign display format. The value can be auto, never, always, or expectZero.

+

compactDisplay

+

string

+

Yes

+

Yes

+

Compact display format. The value can be long or short.

+

notation

+

string

+

Yes

+

Yes

+

Number notation. The value can be standard, scientific, engineering, or compact.

+

localeMatcher

+

string

+

Yes

+

Yes

+

Locale matching algorithm. The value can be lookup or best fit.

+

style

+

string

+

Yes

+

Yes

+

Number display format. The value can be decimal, currency, percent, or unit.

+

numberingSystem

+

string

+

Yes

+

Yes

+

Numbering system.

+

useGrouping

+

boolean

+

Yes

+

Yes

+

Whether to enable grouping for display.

+

miniumumIntegerDigits

+

number

+

Yes

+

Yes

+

Minimum number of integer digits.

+

miniumumFractionDigits

+

number

+

Yes

+

Yes

+

Minimum number of fraction digits.

+

maxiumumFractionDigits

+

number

+

Yes

+

Yes

+

Maximum number of fraction digits.

+

miniumumSignificantDigits

+

number

+

Yes

+

Yes

+

Minimum number of significant digits.

+

maxiumumSignificantDigits

+

number

+

Yes

+

Yes

+

Maximum number of significant digits.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md new file mode 100644 index 0000000000000000000000000000000000000000..d4430fd798d4ef558605cb65e7463d2e1c646921 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -0,0 +1,407 @@ +# Audio Playback and Recording + +## Modules to Import + +``` +import media from '@ohos.multimedia.media'; +``` + +## Required Permissions + +None + +## media.createAudioPlayer + +Creates an **AudioPlayer** instance. + +**Return values** + +| Type | Description | +| --------------------------- | ------------------------------------------------------------ | +| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. | + +**Example** + +``` +var audioplayer = media.createAudioPlayer(); +``` + +## media.createAudioRecorder + +createAudioRecorder(): AudioRecorder + +Creates an **AudioRecorder** instance to control audio recording. + +**Return values** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. | + +**Example** + +``` +var audiorecorder = media.createAudioRecorder(); +``` + +## AudioPlayer + +Manages and plays audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ----------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| src | string | Yes | Yes | Audio media URI. Popular audio formats (mp4, aac, mp3, and ogg) are supported. The value can be a local absolute path starting with **file://**. | +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop playback. | +| currentTime | number | Yes | No | Current playback position. | +| duration | number | Yes | No | Audio duration. | +| state | [AudioState](#audiostate) | Yes | No | Playback status. | + +### play + +play\(\): void + +Starts audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('play', () => { + console.log('Playback starts.'); +}); +audioplayer.play(); +``` + +### pause + +pause\(\): void + +Pauses audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('pause', () => { + console.log('Playback paused.'); +}); +audioplayer.pause(); +``` + + +### stop + +stop\(\): void + +Stops audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('stop',() => { + console.log('Playback stopped.'); +}); +audioplayer.stop(); +``` + + +### seek + +seek\(timeMs: number\): void + +Seeks to the specified playback position. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------------------------- | +| timeMs | number | Yes | Playback position to seek to. | + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('timeupdate', (action) => { + var newTime = audioplayer.currenTime; + if(newTime >= 30000) { + console.info('Seek succeeded. New time: ' + newTime); + } else { + console.info('Seek failed.'); + } +}); +audioplayer.seek(30000); +``` + +### setVolume + +setVolume\(vol: number\): void + +Sets the volume. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%). | + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('volumeChange', () => { + console.log('Playback volume changed.'); +}); +audioplayer.setVolume(1); +``` + +### reset7+ + +reset\(\): void + +Switches the audio resource to be played. + +**Example** + +``` +audioplay.reset(); +``` + +### release + +release\(\): void + +Releases audio resources. + +**Example** + +``` +audioplay.release(); +``` + +### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +Listens for audio playback events. + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback event to listen for. The following events are supported: **play**, **pause**, **stop**, **reset**, **dataLoad**, **finish**, and **volumeChange**.
- The **play** event is triggered when audio playback starts.
- The **pause** event is triggered when audio playback is paused.
- The **stop** event is triggered when audio playback stops.
- The **reset** event is triggered when the player is reset.
- The **dataLoad** event is triggered when audio data is loaded.
- The **finish** event is triggered when audio playback is finished.
- The **volumeChange** event is triggered when the playback volume changes. | +| callback | function | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file://xxx/sounds.mp4'; +audioplayer.on('play', () => { + console.log('Playback starts.'); +}); +audioplayer.play(); +``` + +### on('timeUpdate') + +on(type: 'timeUpdate', callback: Callback\): void + +Listens for audio playback timestamp update events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback event to listen for. Only the **timeUpdate** event is supported.
- The **timeUpdate** event is triggered when the audio playback timestamp is updated. It is also triggered when the **seek** method is called. | +| callback | Callback<number> | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file://xxx/sounds.mp4'; +audioplayer.on('timeupdate', (newTime ) => { + if(newTime >= 30000) { + console.info('Seek succeeded. New time: ' + newTime); + } else { + console.info('Seek failed.'); + } +}); +audioplayer.seek(30000); +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for playback error events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback error event to listen for.
- The **error** event is triggered when an error occurs during audio playback. | +| callback | ErrorCallback | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file:///data/sounds.mp4'; +audioplayer.on('error', (err) => { + console.info('error callback info: ' + err); +}); +audioplayer.setVolume(30000); +``` + + +## AudioState + +Describes the audio playback state. + +| Name | Description | +| ------- | -------------------------- | +| idle | Audio playback is idle. | +| playing | The audio is being played. | +| paused | Audio playback is paused. | +| stopped | Audio playback is stopped. | + +## AudioRecorder + +Provides methods to record audio. Before calling an **AudioRecorder** method, you must use [createAudioRecorder\(\)](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. + +### prepare + +prepare(config: AudioRecorderConfig): void + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------------------------------------------- | --------- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels | + +**Example** + + ``` + let audioRecorderConfig = { + audioEncoder : AAC_LC , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : AAC_ADTS, + uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', + } + audiorecorder.prepare(audioRecorderConfig) + ``` +### start + +start(): void + +Starts audio recording. + +**Example** + +``` +audiorecorder.start(); +``` + +### stop + +stop(): void + +Stops audio recording. + +**Example** + +``` +audiorecorder.stop(); +``` + +### release + +release(): void + +**Example** + +``` +audiorecorder.release(); +``` + +### reset + +reset(): void + +Resets audio recording. + +Before resetting audio recording, you must call **stop\(\)** to stop recording. After audio recording is reset, you must call **prepare\(\)** to set the recording configurations for another recording. + +**Example** + +``` +audiorecorder.reset(); +``` + +### on('prepare' | 'start' | 'stop' | 'release' | 'reset') + +on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void + +Listens for audio recording events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the audio recording event to listen for. The following events are supported: **prepare**, **start**, **stop**, **release**, and **reset**.
- The **prepare** event is triggered when the audio recording preparation is complete.
- The **start** event is triggered when audio recording starts.
- The **stop** event is triggered when audio recording stops.
- The **release** event is triggered when resources related to audio recording are released.
- The **reset** event is triggered when audio recording is reset. | +| callback | function | Yes | Callback used to listen for the audio recording event. | + +**Example** + +``` +audiorecorder.on('prepare', () => { + console.log('Preparation succeeded.'); + audiorecorder.start(); +}); +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for audio recording error events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the audio recording error event to listen for.
- The **error** event is triggered when an error occurs during audio recording. | +| callback | function | Yes | Callback used to listen for the audio recording event. | + +## AudioRecorderConfig + +Describes audio recording configurations. + +| Name | Type | Mandatory | Description | +| ------------------ | --------------------------------------- | --------- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | +| audioEncodeBitRate | number | No | Bit rate for audio encoding. The default value is **48000**. | +| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | +| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | +| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | +| uri | string | Yes | Audio output URI. The following types of URIs are supported:
1. Absolute path:
file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. Path with the file descriptor (FD): file://1 (FD number) | + +## AudioEncoder + +Enumerates audio encoding formats. + +| Name | Default Value | Description | +| ------ | ------------- | ---------------------------------------------- | +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC). | + +## AudioOutputFormat + +Enumerates audio output formats. + +| Name | Default Value | Description | +| -------- | ------------- | ------------------------------------------------------------ | +| MPEG_4 | 2 | MPEG-4. | +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), a transmission stream format of Advanced Audio Coding (AAC) audio. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md new file mode 100644 index 0000000000000000000000000000000000000000..fedc273ec2cf3f56700a6064d9c5ae887fa8351d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -0,0 +1,179 @@ +# Power Management + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import power from '@ohos.power'; +``` + +## Required Permissions + +Shutdown: ohos.permission.SHUTDOWN + +Reboot: ohos.permission.REBOOT + +Reboot and entering the recovery mode: ohos.permission.REBOOT\_RECOVERY + +## power.shutdownDevice + +shutdownDevice\(reason: string\): void + +Shuts down the system. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reason

+

string

+

Yes

+

Reason for system shutdown.

+
+ +- Example + + ``` + power.shutdownDevice("shutdown_test"); + console.info('power_shutdown_device_test success') + ``` + + +## power.rebootDevice + +rebootDevice\(reason: string\): void + +Reboots the system. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reason

+

string

+

Yes

+

Reason for system reboot.

+
+ +- Example + + ``` + power.rebootDevice("reboot_test"); + console.info('power_reboot_device_test success') + ``` + + +## power.isScreenOn + +isScreenOn\(callback: AsyncCallback\): void + +Checks the screen status of the current device. + +- Parameters + + + + + + + + + + + + + + +

Type

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to obtain the return value.

+

The value true indicates that the screen is on, and value false indicates the opposite.

+
+ + +- Example + + ``` + power.isScreenOn((error, screenOn) => { + if (typeof error === "undefined") { + console.info('screenOn status is ' + screenOn); + } else { + console.log('error: ' + error); + } + }) + ``` + + +## power.isScreenOn + +isScreenOn\(\): Promise + +Checks the screen status of the current device. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to asynchronously obtain the return value. The value true indicates that the screen is on, and value false indicates the opposite.

+
+ +- Example + + ``` + power.isScreenOn() + .then(screenOn => { + console.info('screenOn status is ' + screenOn); + }) + .catch(error => { + console.log('error: ' + error); + }) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md new file mode 100644 index 0000000000000000000000000000000000000000..34fc52c05097d07cd12caffa8f2952492cfc95b7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -0,0 +1,777 @@ +# Obtaining Process Information + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import process from '@ohos.process'; +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

egid

+

number

+

Yes

+

No

+

Effective group identifier (EGID) of a process.

+

euid

+

number

+

Yes

+

No

+

Effective user identifier (EUID) of a process.

+

gid

+

number

+

Yes

+

No

+

Group identifier (GID) of a process.

+

uid

+

number

+

Yes

+

No

+

User identifier (UID) of a process.

+

groups

+

number[]

+

Yes

+

No

+

An array with supplementary group IDs.

+

pid

+

number

+

Yes

+

No

+

Process ID (PID) of a process.

+

ppid

+

number

+

Yes

+

No

+

Parent process ID (PPID) of a process.

+
+ +## ChildProcess + +Allows a process to obtain the standard input and output of its child processes, send signals, and close its child processes. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

pid

+

number

+

Yes

+

No

+

PID of the child process.

+

ppid

+

number

+

Yes

+

No

+

PPID of the child process.

+

exitCode

+

number

+

Yes

+

No

+

Exit code of the child process.

+

killed

+

boolean

+

Yes

+

No

+

Whether the parent process successfully sends a signal to the child process to terminate it.

+
+ +### wait + +wait\(\): Promise + +Waits until the child process ends. This method uses a promise to return the exit code of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the exit code of the child process.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls'); + var result = child.wait(); + result.then(val=>{ + console.log("result = " + val); + }) + ``` + + +### getOutput + +getOutput\(\): Promise + +Obtains the standard output of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array>

+

Promise used to return the standard output in a Uint8Array.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls'); + var result = child.wait(); + child.getOutput.then(val=>{ + console.log("child.getOutput = " + val); + }) + ``` + + +### getErrorOutput + +getErrorOutput\(\): Promise + +Obtains the standard error output of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array>

+

Promise used to return the standard error output in a Uint8Array.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('madir test.text'); + var result = child.wait(); + child.getErrorOutput.then(val=>{ + console.log("child.getErrorOutput= " + val); + }) + ``` + + +### close + +close\(\): void + +Closes the child process in running. + +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('sleep 5; ls'); + child.close(); + ``` + + +### kill + +kill\(signal: number | string\): void + +Sends a signal to the specified child process to terminate it. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

signal

+

number | string

+

Yes

+

Number or string to send.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('sleep 5; ls'); + child.kill(9); + ``` + + +## process.runCmd + +runCmd\(command: string, options?: \{ timeout : number, killSignal : number | string, maxBuffer : number \}\) : ChildProcess + +Forks a new process to run a shell command and returns the **ChildProcess** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

command

+

string

+

Yes

+

Shell command to run.

+

options

+

Object

+

No

+

Related parameters.

+
+ + **Table 1** options + + + + + + + + + + + + + + + + + + + + + + + + +

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.

+

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 values + + + + + + + + + + +

Type

+

Description

+

ChildProcess

+

ChildProcess object.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls', { maxBuffer : 2 }); + var result = child.wait(); + child.getOutput.then(val=>{ + console.log("child.getOutput = " + val); + } + ``` + + +## process.abort + +abort\(\): void + +Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method. + +- Example + + ``` + import process from '@ohos.process'; + process.abort(); + ``` + + +## process.on + +on\(type: string, listener: EventListener\): void + +Stores the events triggered by the user. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the events to store.

+

listener

+

EventListener

+

Yes

+

Callback invoked to return the event.

+
+ + **Table 2** EventListener + + + + + + + + + + +

Name

+

Description

+

EventListener = (evt: Object) => void

+

Event to store.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.on("data", (e)=>{ + console.log("data callback"); + }) + ``` + + +## process.off + +off\(type: string\): boolean + +Deletes the event stored by the user. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to delete.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the event is deleted.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.on("data", (e)=>{ + console.log("data callback"); + }) + var result = process.off("data"); + ``` + + +## process.exit + +exit\(code: number\): void + +Terminates a process. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

code

+

number

+

Yes

+

Exit code of the process.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.exit(0); + ``` + + +## process.cwd + +cwd\(\): string + +Obtains the working directory of the process. + +- Example + + ``` + import process from '@ohos.process'; + var path = process.cwd(); + ``` + + +## process.chdir + +chdir\(dir: string\): void + +Changes the working directory of the process. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dir

+

string

+

Yes

+

New working directory.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.chdir('/system'); + ``` + + +## process.uptime + +uptime\(\): number + +Obtains the running time of the process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Running time of the process, in seconds.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var time = process.uptime(); + ``` + + +## process.kill + +kill\(pid: number, signal: number\): boolean + +Sends a signal to the specified process to terminate it. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pid

+

number

+

Yes

+

PID of the process, to which the signal will be sent.

+

signal

+

number

+

Yes

+

Signal to send.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the signal is sent successfully.

+
+ +- Example + + ``` + import process from '@ohos.process' + var pres = process.pid + var result = that.kill(pres, 28) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 69cac33509d195b8a3160f72b127a8ea17ac448c..0c5c2e4e31605656adb3a031425c6bdb0394ebdd 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -2,8 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d90f8aef6a156bfc2eb68a8d639aa001831d4f11 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -0,0 +1,1214 @@ +# Resource Manager + +>![](../../public_sys-resources/icon-note.gif) **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. + + +## Modules to Import + +``` +import resourceManager from '@ohos.resourceManager'; +``` + +## Required Permissions + +None + +## resourceManager.getResourceManager + +getResourceManager\(callback: AsyncCallback\): void + +Obtains the **ResourceManager** object of the current application. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<ResourceManager>

+

Yes

+

Asynchronous callback used to return the ResourceManager object.

+
+ + +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(bundleName: string, callback: AsyncCallback\): void + +Obtains the **ResourceManager** object of the specified application. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the specified application.

+

callback

+

AsyncCallback<ResourceManager>

+

Yes

+

Asynchronous callback used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager("com.example.myapplication", (error, mgr) => { + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(\): Promise + +Obtains the **ResourceManager** object of the current application. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResourceManager>

+

Promise used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager().then(mgr => { + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }).catch(error => { + console.log(error); + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(bundleName: string\): Promise + +Obtains the **ResourceManager** object of the specified application. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the specified application.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResourceManager>

+

Promise used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager("com.example.myapplication").then(mgr => { + + }).catch(error => { + + }); + ``` + + +## Direction + +Enumerates screen directions. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DIRECTION_VERTICAL

+

0

+

Portrait

+

DIRECTION_HORIZONTAL

+

1

+

Landscape

+
+ +## DeviceType + +Enumerates device types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DEVICE_TYPE_PHONE

+

0x00

+

Phone

+

DEVICE_TYPE_TABLET

+

0x01

+

Tablet

+

DEVICE_TYPE_CAR

+

0x02

+

Head unit

+

DEVICE_TYPE_PC

+

0x03

+

PC

+

DEVICE_TYPE_TV

+

0x04

+

Smart TV

+

DEVICE_TYPE_WEARABLE

+

0x06

+

Wearable

+
+ +## ScreenDensity + +Enumerates screen density types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SCREEN_SDPI

+

120

+

Screen density with small-scale dots per inch (SDPI).

+

SCREEN_MDPI

+

160

+

Screen density with medium-scale dots per inch (MDPI)

+

SCREEN_LDPI

+

240

+

Screen density with large-scale dots per inch (LDPI).

+

SCREEN_XLDPI

+

320

+

Screen density with extra-large-scale dots per inch (XLDPI).

+

SCREEN_XXLDPI

+

480

+

Screen density with extra-extra-large-scale dots per inch (XXLDPI).

+

SCREEN_XXXLDPI

+

640

+

Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).

+
+ +## Configuration + +Provides the device configuration. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

direction

+

Direction

+

Yes

+

No

+

Screen direction of the current device.

+

locale

+

string

+

Yes

+

No

+

Current system language.

+
+ +## DeviceCapability + +Provides the device capability. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

screenDensity

+

ScreenDensity

+

Yes

+

No

+

Screen density of the current device.

+

deviceType

+

DeviceType

+

Yes

+

No

+

Type of the current device.

+
+ +## ResourceManager + +Provides the capability of accessing application resources. + +### getString + +getString\(resId: number, callback: AsyncCallback\): void + +Obtains the string corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getString + +getString\(resId: number\): Promise + +Obtains the string corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

String corresponding to the resource ID.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getString(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getStringArray + +getStringArray\(resId: number, callback: AsyncCallback\>\): void + +Obtains the array of strings corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<Array<string>>

+

Yes

+

Asynchronous callback used to return the obtained array of strings.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getStringArray + +getStringArray\(resId: number\): Promise\> + +Obtains the array of strings corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Array<string>>

+

Array of character strings corresponding to the specified resource ID.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getMedia + +getMedia\(resId: number, callback: AsyncCallback\): void + +Obtains the content of the media file corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<Array<Uint8Array>>

+

Yes

+

Asynchronous callback used to return the content of the obtained media file.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getMedia + +getMedia\(resId: number\): Promise + +Obtains the content of the media file corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Array<Uint8Array>>

+

Promise used to return the content of the obtained media file.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getMediaBase64 + +getMediaBase64\(resId: number, callback: AsyncCallback\): void + +Obtains the Base64 code of the image corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained Base64 code of the image.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getMediaBase64 + +getMediaBase64\(resId: number\): Promise + +Obtains the Base64 code of the image corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the obtained Base64 code of the image.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getConfiguration + +getConfiguration\(callback: AsyncCallback\): void + +Obtains the device configuration. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Configuration>

+

Yes

+

Asynchronous callback used to return the obtained device configuration.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getConfiguration((error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getConfiguration + +getConfiguration\(\): Promise + +Obtains the device configuration. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Configuration>

+

Promise used to return the device configuration.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getConfiguration().then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getDeviceCapability + +getDeviceCapability\(callback: AsyncCallback\): void + +Obtains the device capability. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<DeviceCapability>

+

Yes

+

Asynchronous callback used to return the obtained device capability.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getDeviceCapability((error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getDeviceCapability + +getDeviceCapability\(\): Promise + +Obtains the device capability. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<DeviceCapability>

+

Promise used to return the obtained device capability.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getDeviceCapability().then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getPluralString + +getPluralString\(resId: number, num: number, callback: AsyncCallback\): void + +Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

num

+

number

+

Yes

+

Number that determines the plural or singular form.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained singular-plural string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString(0x1000000, 1, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getPluralString + +getPluralString\(resId: number, num: number\): Promise + +Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

num

+

number

+

Yes

+

Number that determines the plural or singular form.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the obtained singular-plural string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString(0x1000000, 1).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md new file mode 100644 index 0000000000000000000000000000000000000000..9c99661eb2ae5544557b53509bcb265d4c2c094e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -0,0 +1,402 @@ +# Running Lock + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import runninglock from '@ohos.runningLock'; +``` + +## Required Permissions + +To request or use a running lock, you must declare the **ohos.permission.RUNNING\_LOCK** permission. + +## RunningLockType + +Enumerates the types of running locks. + + + + + + + + + + + + + + + + +

Description

+

Default Value

+

Description

+

BACKGROUND

+

1

+

A lock that prevents the system from hibernating.

+

PROXIMITY_SCREEN_CONTROL

+

2

+

A lock that determines whether to turn on or off the screen based on the distance away from the screen.

+
+ +## runninglock.isRunningLockTypeSupported + +isRunningLockTypeSupported\(type: RunningLockType, callback: AsyncCallback\): void + +Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to obtain the return value.

+

The value true indicates that the specified type of RunningLock is supported, and value false indicates the opposite.

+
+ +- Example + + ``` + runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { + if (typeof error === "undefined") { + console.info('BACKGROUND support status is ' + supported); + } else { + console.log('error: ' + error); + } + }) + ``` + + +## runninglock.isRunningLockTypeSupported + +isRunningLockTypeSupported\(type: RunningLockType\): Promise + +Checks whether a specified type of **RunningLock** is supported. This function uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to asynchronously obtain the return value. The value true indicates that the specified type of RunningLock is supported, and value false indicates the opposite.

+
+ +- Example + + ``` + runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) + .then(supported => { + console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); + }) + .catch(error => { + console.log('error: ' + error); + }); + ``` + + +## runninglock.createRunningLock + +createRunningLock\(name: string, type: RunningLockType, callback: AsyncCallback\): void + +Creates a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RunningLock object.

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object to be created.

+

callback

+

AsyncCallback<RunningLock>

+

Yes

+

Callback used to obtain the return value.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runninglock => { + var used = runninglock.isUsed(); + console.info('runninglock is used: ' + used); + runninglock.lock(500); + used = runninglock.isUsed(); + console.info('after lock runninglock is used ' + used); + }) + .catch(error => { + console.log('create runningLock test error: ' + error); + }) + ``` + + +## runninglock.createRunningLock + +createRunningLock\(name: string, type: RunningLockType\): Promise + +Creates a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RunningLock object.

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object to be created.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<RunningLock>

+

Promise used to asynchronously obtain the returned RunningLock object.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runninglock => { + console.info('create runningLock success'); + }) + .catch(error => { + console.log('create runningLock test error: ' + error); + }) + ``` + + +## RunningLock + +Defines a **RunningLock** object. + +### lock + +lock\(timeout: number\): void + +Locks and holds a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timeout

+

number

+

No

+

Duration for locking and holding the RunningLock object.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + runningLock.lock(100) + console.info('create runningLock success') + }) + .catch(error => { + console.log('Lock runningLock test error: ' + error) + }); + ``` + + +### unlock + +unlock\(\): void + +Releases a **Runninglock** object. + +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + runningLock.unlock() + console.info('unLock runningLock success') + }) + .catch(error => { + console.log('unLock runningLock test error: ' + error) + }); + ``` + + +### isUsed + +isUsed\(\): boolean + +Checks the status of the **Runninglock** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the Runninglock object is held; returns false if the Runninglock object is released.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + var used = runningLock.isUsed() + console.info('runningLock used status: ' + used) + }) + .catch(error => { + console.log('runningLock isUsed test error: ' + error) + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..6c3f45743f9c1e4144d3a8e70d1c6aff8a3d9ab5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -0,0 +1,3748 @@ +# Sensors + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The APIs of this module are supported since API version 8. + +## Modules to Import + +``` +import sensor from '@ohos.sensor'; +``` + +## Required Permissions + +To use the pedometer sensor, you must declare the **ohos.permission.ACTIVITY\_MOTION** permission. + +To use the heart rate sensor, you must declare the **ohos.permission.READ\_HEALTH\_DATA** permission. + +To use the acceleration sensor, you must declare the **ohos.permission.ACCELEROMETER** permission. + +To use the gyroscope sensor, you must declare the **ohos.permission.GYROSCOPE** permission. + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER, callback: AsyncCallback,options?: Options\): void + +Subscribes to acceleration sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER.

+

callback

+

AsyncCallback<AccelerometerResponse>

+

Yes

+

Callback used to return the acceleration sensor data. The reported data type in the callback is AccelerometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_LINEAR_ACCELERATION.

+

callback

+

AsyncCallback<LinearAccelerometerResponse>

+

Yes

+

Callback used to return the linear acceleration sensor data. The reported data type in the callback is LinearAccelerometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED.

+

callback

+

AsyncCallback<AccelerometerUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is AccelerometerUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GRAVITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_GRAVITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to gravity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GRAVITY.

+

callback

+

AsyncCallback<GravityResponse>

+

Yes

+

Callback used to return the gravity sensor data. The reported data type in the callback is GravityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_GRAVITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE, callback: AsyncCallback, options?: Options\): void + +Subscribes to gyroscope sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE.

+

callback

+

AsyncCallback<GyroscopeResponse>

+

Yes

+

Callback used to return the gyroscope sensor data. The reported data type in the callback is GyroscopeResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_GUROSCOPE,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED.

+

callback

+

AsyncCallback<GyroscopeUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is GyroscopeUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_SIGNIFICANT_MOTION.

+

callback

+

AsyncCallback<SignificantMotionResponse>

+

Yes

+

Callback used to return the significant motion sensor data. The reported data type in the callback is SignificantMotionResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER_DETECTION.

+

callback

+

AsyncCallback<PedometerDetectResponse>

+

Yes

+

Callback used to return the pedometer detection sensor data. The reported data type in the callback is PedometerDetectResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(error,data){ + if (error) { + console.error(""Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER, callback: AsyncCallback, options?: Options\): void + +Subscribes to pedometer sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER.

+

callback

+

AsyncCallback<PedometerResponse>

+

Yes

+

Callback used to return the pedometer sensor data. The reported data type in the callback is PedometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the number of steps. + console.info('Steps: ' + data.steps); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_TEMPERATURE.

+

callback

+

AsyncCallback<AmbientTemperatureResponse>

+

Yes

+

Callback used to return the ambient temperature sensor data. The reported data type in the callback is AmbientTemperatureResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the temperature. + console.info('Temperature: ' + data.temperature); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD, callback: AsyncCallback,options?: Options\): void + +Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD.

+

callback

+

AsyncCallback<MagneticFieldResponse>

+

Yes

+

Callback used to return the magnetic field sensor data. The reported data type in the callback is MagneticFieldResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED,callback:AsyncCallback, options: Options\): void + +Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED.

+

callback

+

AsyncCallback<MagneticFieldUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is MagneticFieldUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + ensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} // Set the data reporting frequency. + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PROXIMITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PROXIMITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to proximity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PROXIMITY.

+

callback

+

AsyncCallback<ProximityResponse>

+

Yes

+

Callback used to return the proximity sensor data. The reported data type in the callback is ProximityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the proximity. + console.info('Distance: ' + data.distance); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_HUMIDITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_HUMIDITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to humidity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HUMIDITY.

+

callback

+

AsyncCallback<HumidityResponse>

+

Yes

+

Callback used to return the humidity sensor data. The reported data type in the callback is HumidityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the humidity. + console.info('Humidity: ' + data.humidity); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_BAROMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_BAROMETER, callback: AsyncCallback,options?: Options\): void + +Subscribes to barometer sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_BAROMETER.

+

callback

+

AsyncCallback<BarometerResponse>

+

Yes

+

Callback used to return the barometer sensor data. The reported data type in the callback is BarometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_BAROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the atmospheric pressure. + console.info('Atmospheric pressure: ' + data.pressure); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_HALL\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_HALL, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HALL.

+

callback

+

AsyncCallback<HallResponse>

+

Yes

+

Callback used to return the Hall effect sensor data. The reported data type in the callback is HallResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_HALL,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the status. + console.info('Status: ' + data.status); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_LIGHT.

+

callback

+

AsyncCallback<LightResponse>

+

Yes

+

Callback used to return the ambient light sensor data. The reported data type in the callback is LightResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the illumination. + console.info(''Illumination: ' + data.intensity); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ORIENTATION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_ORIENTATION, callback: AsyncCallback, options?: Options\): void + +Subscribes to orientation sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ORIENTATION.

+

callback

+

AsyncCallback<OrientationResponse>

+

Yes

+

Callback used to return the orientation sensor data. The reported data type in the callback is OrientationResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR,callback:AsyncCallback,options?: Options\): void + +Subscribes to rotation vector data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ROTATION_VECTOR.

+

callback

+

AsyncCallback<RotationVectorResponse>

+

Yes

+

Callback used to return the rotation vector sensor data. The reported data type in the callback is RotationVectorResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION, callback: AsyncCallback,options?: Options\): void + +Subscribes to wear detection data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_WEAR_DETECTION.

+

callback

+

AsyncCallback<WearDetectionResponse>

+

Yes

+

Callback used to return the wear detection sensor data. The reported data type in the callback is WearDetectionResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the wear status. + console.info('Wear status: ' + data.value); + } + {interval: 10000000} + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER, callback: AsyncCallback\): void + +Subscribes to only one acceleration sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER.

+

callback

+

AsyncCallback<AccelerometerResponse>

+

Yes

+

One-shot callback used to return the acceleration sensor data. The reported data type in the callback is AccelerometerResponse.

+
+ + +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION,callback:AsyncCallback\): void + +Subscribes to only one data change of the linear acceleration sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_LINEAR_ACCELERATION.

+

callback

+

AsyncCallback<LinearAccelerometerResponse>

+

Yes

+

One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is LinearAccelerometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated acceleration sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED.

+

callback

+

AsyncCallback<AccelerometerUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is AccelerometerUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GRAVITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_GRAVITY, callback: AsyncCallback\): void + +Subscribes to only one gravity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GRAVITY.

+

callback

+

AsyncCallback<GravityResponse>

+

Yes

+

One-shot callback used to return the gravity sensor data. The reported data type in the callback is GravityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GRAVITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE, callback: AsyncCallback\): void + +Subscribes to only one gyroscope sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE.

+

callback

+

AsyncCallback<GyroscopeResponse>

+

Yes

+

One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is GyroscopeResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated gyroscope sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED.

+

callback

+

AsyncCallback<GyroscopeUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is GyroscopeUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION,callback:AsyncCallback\): void + +Subscribes to only one data change of the significant motion sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_SIGNIFICANT_MOTION.

+

callback

+

AsyncCallback<SignificantMotionResponse>

+

Yes

+

One-shot callback used to return the significant motion sensor data. The reported data type in the callback is SignificantMotionResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION,callback:AsyncCallback\): void + +Subscribes to only one data change of the pedometer detection sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER_DETECTION.

+

callback

+

AsyncCallback<PedometerDetectResponse>

+

Yes

+

One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is PedometerDetectResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER, callback: AsyncCallback\): void + +Subscribes to only one pedometer sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER.

+

callback

+

AsyncCallback<PedometerResponse>

+

Yes

+

One-shot callback used to return the pedometer sensor data. The reported data type in the callback is PedometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the number of steps. + console.info('Steps: ' + data.steps); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE,callback:AsyncCallback\): void + +Subscribes to only one data change of the ambient temperature sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_TEMPERATURE.

+

callback

+

AsyncCallback<AmbientTemperatureResponse>

+

Yes

+

One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is AmbientTemperatureResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the temperature data. + console.info('Temperature: ' + data.temperature); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD, callback: AsyncCallback\): void + +Subscribes to only one data change of the magnetic field sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD.

+

callback

+

AsyncCallback<MagneticFieldResponse>

+

Yes

+

One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is MagneticFieldResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated magnetic field sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED.

+

callback

+

AsyncCallback<MagneticFieldUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is MagneticFieldUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PROXIMITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_PROXIMITY, callback: AsyncCallback\): void + +Subscribes to only one proximity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PROXIMITY.

+

callback

+

AsyncCallback<ProximityResponse>

+

Yes

+

One-shot callback used to return the proximity sensor data. The reported data type in the callback is ProximityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the proximity. + console.info('Distance: ' + data.distance); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HUMIDITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HUMIDITY, callback: AsyncCallback\): void + +Subscribes to only one humidity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HUMIDITY.

+

callback

+

AsyncCallback<HumidityResponse>

+

Yes

+

One-shot callback used to return the humidity sensor data. The reported data type in the callback is HumidityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HUMIDITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the humidity. + console.info('Humidity: ' + data.humidity); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_BAROMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_BAROMETER, callback: AsyncCallback\): void + +Subscribes to only one barometer sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_BAROMETER.

+

callback

+

AsyncCallback<BarometerResponse>

+

Yes

+

One-shot callback used to return the barometer sensor data. The reported data type in the callback is BarometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_BAROMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the atmospheric pressure. + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HALL\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HALL, callback: AsyncCallback\): void + +Subscribes to only one data change of the Hall effect sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HALL.

+

callback

+

AsyncCallback<HallResponse>

+

Yes

+

One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is HallResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HALL, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the status. + console.info('Status: ' + data.status); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT, callback: AsyncCallback\): void + +Subscribes to only one data change of the ambient light sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_LIGHT.

+

callback

+

AsyncCallback<LightResponse>

+

Yes

+

One-shot callback used to return the ambient light sensor data. The reported data type in the callback is LightResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the illumination. + console.info('Illumination: ' + data.intensity); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ORIENTATION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ORIENTATION, callback: AsyncCallback\): void + +Subscribes to only one orientation sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ORIENTATION.

+

callback

+

AsyncCallback<OrientationResponse>

+

Yes

+

One-shot callback used to return the orientation sensor data. The reported data type in the callback is OrientationResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ORIENTATION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR, callback: AsyncCallback\): void + +Subscribes to only one rotation vector data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ROTATION_VECTOR.

+

callback

+

AsyncCallback<RotationVectorResponse>

+

Yes

+

One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is RotationVectorResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HEART\_RATE\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HEART\_RATE, callback: AsyncCallback\): void + +Subscribes to only one data change of the heart rate sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HEART_RATE.

+

callback

+

AsyncCallback<HeartRateResponse>

+

Yes

+

One-shot callback used to return the heart rate sensor data. The reported data type in the callback is HeartRateResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HEART_RATE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the heart rate. + console.info("Heart rate: " + data.heartRate); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION, callback: AsyncCallback\): void + +Subscribes to only one data change of the wear detection sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_WEAR_DETECTION.

+

callback

+

AsyncCallback<WearDetectionResponse>

+

Yes

+

One-shot callback used to return the wear detection sensor data. The reported data type in the callback is WearDetectionResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(error, data) { + if (error) { + console.error("Failed to register data, error code is" + error.code + ", message: " + error.message); + return; + } + // Print the wear status. + console.info("Wear status: "+ data.value); + } + ); + ``` + + +## sensor.off + +off\(type: SensorType, callback?: AsyncCallback\): void + +Unsubscribes from sensor data changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to unsubscribe from.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result.

+
+ +- Example + + ``` + sensor.off(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) { + if (error) { + console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info("Succeeded in unsubscribing from acceleration sensor data."); + } + ); + + ``` + + +## SensorType + +Enumerates the sensor types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SENSOR_TYPE_ID_ACCELEROMETER

+

1

+

Acceleration sensor.

+

SENSOR_TYPE_ID_GYROSCOPE

+

2

+

Gyroscope sensor.

+

SENSOR_TYPE_ID_AMBIENT_LIGHT

+

5

+

Ambient light sensor.

+

SENSOR_TYPE_ID_MAGNETIC_FIELD

+

6

+

Magnetic field sensor.

+

SENSOR_TYPE_ID_BAROMETER

+

8

+

Barometer sensor.

+

SENSOR_TYPE_ID_HALL

+

10

+

Hall effect sensor.

+

SENSOR_TYPE_ID_PROXIMITY

+

12

+

Proximity sensor.

+

SENSOR_TYPE_ID_HUMIDITY

+

13

+

Humidity sensor.

+

SENSOR_TYPE_ID_ORIENTATION

+

256

+

Orientation sensor.

+

SENSOR_TYPE_ID_GRAVITY

+

257

+

Gravity sensor.

+

SENSOR_TYPE_ID_LINEAR_ACCELERATION

+

258

+

Linear acceleration sensor.

+

SENSOR_TYPE_ID_ROTATION_VECTOR

+

259

+

Rotation vector sensor.

+

SENSOR_TYPE_ID_AMBIENT_TEMPERATURE

+

260

+

Ambient temperature sensor.

+

SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED

+

261

+

Uncalibrated magnetic field sensor.

+

SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED

+

263

+

Uncalibrated gyroscope sensor.

+

SENSOR_TYPE_ID_SIGNIFICANT_MOTION

+

264

+

Significant motion sensor.

+

SENSOR_TYPE_ID_PEDOMETER_DETECTION

+

265

+

Pedometer detection sensor.

+

SENSOR_TYPE_ID_PEDOMETER

+

266

+

Pedometer sensor.

+

SENSOR_TYPE_ID_HEART_RATE

+

278

+

Heart rate sensor.

+

SENSOR_TYPE_ID_WEAR_DETECTION

+

280

+

Wear detection sensor.

+

SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED

+

281

+

Uncalibrated acceleration sensor.

+
+ +## AccelerometerResponse + +Describes the acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## LinearAccelerometerResponse + +Describes the linear acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## AccelerometerUncalibratedResponse + +Describes the uncalibrated acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## GravityResponse + +Describes the gravity sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## OrientationResponse + +Describes the orientation sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## RotationVectorResponse + +Describes the rotation vector sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## GyroscopeResponse + +Describes the gyroscope sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## GyroscopeUncalibratedResponse + +Describes the uncalibrated gyroscope sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## SignificantMotionResponse + +Describes the significant motion sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

scalar

+

number

+

Yes

+

Yes

+

Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value 0 means that the device does not have a significant motion, and 1 means the opposite.

+
+ +## ProximityResponse + +Describes the proximity sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

distance

+

number

+

Yes

+

Yes

+

Proximity between the visible object and the device monitor. The value 0 means the two are close to each other, and 1 means that they are far away from each other.

+
+ +## LightResponse + +Describes the ambient light sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

intensity

+

number

+

Yes

+

Yes

+

Illumination, in lux.

+
+ +## HallResponse + +Describes the Hall effect sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

status

+

number

+

Yes

+

Yes

+

Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value 0 means that a magnetic field exists around the device, and 1 means the opposite.

+
+ +## MagneticFieldResponse + +Describes the magnetic field sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## MagneticFieldUncalibratedResponse + +Describes the uncalibrated magnetic field sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## PedometerResponse + +Describes the pedometer sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

steps

+

number

+

Yes

+

Yes

+

Number of steps. The number starts from 0 each time the device restarts.

+
+ +## HumidityResponse + +Describes the humidity sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

humidity

+

number

+

Yes

+

Yes

+

Ambient relative humidity, in a percentage (%).

+
+ +## PedometerDetectResponse + +Describes the pedometer detection sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

scalar

+

number

+

Yes

+

Yes

+

Pedometer detection. This parameter specifies whether a user takes a step. The value 0 means that the user does not take a step, and 1 means that the user takes a step.

+
+ +## AmbientTemperatureResponse + +Describes the ambient temperature sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

temperature

+

number

+

Yes

+

Yes

+

Ambient temperature, in degree Celsius.

+
+ +## BarometerResponse + +Describes the barometer sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

pressure

+

number

+

Yes

+

Yes

+

Atmospheric pressure, in pascal.

+
+ +## HeartRateResponse + +Describes the heart rate sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

heartRate

+

number

+

Yes

+

Yes

+

Heart rate, in beats per minute.

+
+ +## WearDetectionResponse + +Describes the wear detection sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

value

+

boolean

+

Yes

+

Yes

+

Whether the device is being worn. The value true means that the device is being worn, and false means the opposite.

+
+ +## Options + +Describes the sensor data reporting frequency. + + + + + + + + + + + + +

Name

+

Type

+

Description

+

interval

+

number

+

Frequency at which a sensor reports data. The default value is 200,000,000 ns.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 9d27fea1ef66d7e3727e2b3cfcaf22175668ea6c..bf7ff76d1586154ed1aff89465935d259901f5c9 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2,8 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index a45f89399ee9e2c5d7cd71585d08f9fb6f9c4c1c..82c9622de028bc4cf9c8e772a0f25301a8492534 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -2,9 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. -> ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md new file mode 100644 index 0000000000000000000000000000000000000000..32637f989dafb9d3b0a8c48796d1cc62000f5cca --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -0,0 +1,458 @@ +# systemParameter + +## Modules to Import + +``` +import parameter from '@ohos.systemParameter' +``` + +## Required Permissions + +None + +## parameter.getSync + +getSync\(key: string, def?: string\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

string

+

System attribute value. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.

+
+ +**Example** + +``` +try { + var info = parameter.getSync("test.parameter.key"); + console.log(JSON.stringify(info)); +}catch(e){ + console.log("getSync unexpected error: " + e); +} +``` + +## parameter.get + +get\(key: string, callback: AsyncCallback\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback function

+
+ +**Example** + +``` +try { + parameter.get("test.parameter.key", function (err, data) { + if (err == undefined) { + console.log("get test.parameter.key value success:" + data) + } else { + console.log(" get test.parameter.key value err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + +## parameter.get + +get\(key: string, def: string, callback: AsyncCallback\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

Yes

+

Default value

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback function

+
+ +**Example** + +``` +try { + parameter.get("test.parameter.key", "default", function (err, data) { + if (err == undefined) { + console.log("get test.parameter.key value success:" + data) + } else { + console.log(" get test.parameter.key value err:" + err.code) + } + }); +}catch(e){ + console.log("get unexpected error:" + e) +} +``` + +## parameter.get + +get\(key: string, def?: string\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise, which is used to obtain the result asynchronously

+
+ +**Example** + +``` +try { + var p = parameter.get("test.parameter.key"); + p.then(function (value) { + console.log("get test.parameter.key success: " + value); + }).catch(function (err) { + console.log("get test.parameter.key error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + +## parameter.setSync + +setSync\(key: string, value: string\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

value

+

string

+

Yes

+

System attribute value to set

+
+ +**Example** + +``` +try { + parameter.setSync("test.parameter.key", "default"); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + +## parameter.set + +set\(key: string, value: string, callback: AsyncCallback\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

Yes

+

Default value

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback function.

+
+ +**Example** + +``` +try { + parameter.set("test.parameter.key", "testValue", function (err, data) { + if (err == undefined) { + console.log("set test.parameter.key value success :" + data) + } else { + console.log("set test.parameter.key value err:" + err.code) + }}); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + +## parameter.set + +set\(key: string, def?: string\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise, which is used to obtain the result asynchronously

+
+ +**Example** + +``` +try { + var p = para.set("test.parameter.key", "testValue"); + p.then(function (value) { + console.log("set test.parameter.key success: " + value); + }).catch(function (err) { + console.log(" set test.parameter.key error: " + err.code); + }); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md new file mode 100644 index 0000000000000000000000000000000000000000..e851eec1055856e6d5a97f45bb45199143ea742d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -0,0 +1,379 @@ +# Setting the System Time + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The APIs of this module are supported since API version 7. + +## Applicable Devices + + + + + + + + + + + + + + +

Phone

+

Tablet

+

Smart TV

+

Wearable

+

Yes

+

Yes

+

Yes

+

Yes

+
+ +## Modules to Import + +``` +import systemTime from '@ohos.systemTime'; +``` + +## systemTime.setTime + +setTime\(time : number, callback : AsyncCallback\) : void + +Set the system time. You must have the ohos.permission.SET\_TIME permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

time

+

number

+

Yes

+

Timestamp to set, in milliseconds

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + // Set the date and time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time, (error, data) => { + if (error) { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + return; + } + console.log(`success to systemTime.setTime: ` + JSON.stringify(data)); + }); + ``` + + +## systemTime.setTime + +setTime\(time : number\) : Promise + +Set the system time. You must have the ohos.permission.SET\_TIME permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

time

+

number

+

Yes

+

Timestamp to set, in milliseconds

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + // Set the date and time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time).then((data) => { + console.log(`success to systemTime.setTime: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + }); + ``` + + +## systemTime.setDate + +setDate\(date: Date, callback: AsyncCallback\): void + +Set the system date. You must have the ohos.permission.SET\_TIME permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Target date

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + var data = new Date("October 13, 2020 11:13:00"); + systemTime.setDate(data,(error, data) => { + if (error) { + console.error('SystemTimePlugin setDate failed because ' + JSON.stringify(error)); + return; + } + console.info('SystemTimePlugin setDate success data : ' + JSON.stringify(data)); + }); + ``` + + +## systemTime.setDate + +setDate\(date: Date\): Promise + +Set the system date. You must have the ohos.permission.SET\_TIME permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Target date

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + var data = new Date("October 13, 2020 11:13:00"); + systemTime.setDate(data).then((value) => { + console.log(`SystemTimePlugin success to systemTime.setDate: ` + JSON.stringify(value)); + }).catch((error) => { + console.error(`SystemTimePlugin failed to systemTime.setDate because: ` + JSON.stringify(error)); + }); + ``` + + +## systemTime.setTimezone + +setTimezone\(timezone: string, callback: AsyncCallback\): void + +Set the system time zone. You must have the ohos.permission.SET\_TIME\_ZONE permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timezone

+

string

+

Yes

+

System time zone

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + systemTime.setTimezone('Asia/Shanghai', (error, data) => { + if (error) { + console.error('SystemTimePlugin setTimezone failed because ' + JSON.stringify(error)); + return; + } + console.info('SystemTimePlugin setTimezone success data : ' + JSON.stringify(data)); + }); + ``` + + +## systemTime.setTimezone + +setTimezone\(timezone: string\): Promise + +Set the system time zone. You must have the ohos.permission.SET\_TIME\_ZONE permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timezone

+

string

+

Yes

+

System time zone

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + systemTime.setTimezone('Asia/Shanghai').then((data) => { + console.log(`SystemTimePlugin success to systemTime.setTimezone: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`SystemTimePlugin failed to systemTime.setTimezone because: ` + JSON.stringify(error)); + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md new file mode 100644 index 0000000000000000000000000000000000000000..384dfa9e330de1793f8a2ebb6515c79e0096615a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -0,0 +1,934 @@ +# URL String Parsing + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import Url from '@ohos.url' +``` + +## Required Permissions + +None + +## URLSearchParams + +### constructor + +constructor\(init?: string\[\]\[\] | Record | string | URLSearchParams\) + +Creates a **URLSearchParams** instance. + +- Parameters + + + + + + + + + + + + + + +

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
+
+ +- Example + + ``` + var objectParams = new URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); + var objectParams1 = new URLSearchParams({"fod" : 1 , "bard" : 2}); + var objectParams2 = new URLSearchParams('?fod=1&bard=2'); + var urlObject = new URL('https://developer.mozilla.org/?fod=1&bard=2'); + var params = new URLSearchParams(urlObject .search); + ``` + + +### append + +append\(name: string, value: string\): void + +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.

+
+ +- Example + + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.append('fod', 3); + ``` + + +### delete + +delete\(name: string\): void + +Deletes key-value pairs of the specified key. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Key of the key-value pairs to delete.

+
+ + +- Example + + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsobject = new URLSearchParams(urlObject.search.slice(1)); + paramsobject.delete('foo'); + ``` + + +### getAll + +getAll\(name: string\): string\[\] + +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.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

string[]

+

All key-value pairs matching the specified key.

+
+ + +- Example + + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.append('fod', 3); // Add a second value for the foo parameter. + console.log(params.getAll('fod')) // Output ["1","3"]. + ``` + + +### entries + +entries\(\): IterableIterator<\[string, string\]\> + +Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value, respectively. + +- Return values + + + + + + + + + + +

Type

+

Description

+

IterableIterator<[string, string]>

+

An ES6 iterator.

+
+ + +- Example + + ``` + var searchParamsObject = new URLSearchParams("keyName1=valueName1&keyName2=valueName2"); + for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs + console.log(pair[0]+ ', '+ pair[1]); + } + ``` + + +### forEach + +forEach\(callbackfn: \(value: string, key: string, searchParams: Object\) =\> void, thisArg?: Object\): void + +Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. + +- 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.

+
+ + **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.

+
+ +- Example + + ``` + const myURLObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + myURLObject.searchParams.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.searchParams === searchParams); + }); + ``` + + +### get + +get\(name: string\): string | null + +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.

+
+ +- Return values + + + + + + + + + + + + + +

Type

+

Description

+

string

+

Returns the value of the first key-value pair if obtained.

+

null

+

Returns null if no value is obtained.

+
+ +- Example + + ``` + var paramsOject = new URLSearchParams(document.location.search.substring(1)); + var name = paramsOject.get("name"); // is the string "Jonathan" + var age = parseInt(paramsOject.get("age"), 10); // is the number 18 + var address = paramsOject.get("address"); // null + ``` + + +### has + +has\(name: string\): boolean + +Checks whether a key has a value. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Key specified to search for its value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the value exists; returns false otherwise.

+
+ +- Example + + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.has('bard') === true; + ``` + + +### set + +set\(name: string, value: string\): void + +Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Key of the value to set.

+

value

+

string

+

Yes

+

Value to set.

+
+ + +- Example + + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.set('baz', 3); // Add a third parameter. + ``` + + +### sort + +sort\(\): void + +Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns **undefined**. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. + +- Example + + ``` + var searchParamsObject = new URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object + searchParamsObject.sort(); // Sort the key/value pairs + console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 + ``` + + +### keys + +keys\(\): IterableIterator + +Obtains an ES6 iterator that contains the keys of all the key-value pairs. + +- Return values + + + + + + + + + + +

Type

+

Description

+

IterableIterator<string>

+

ES6 iterator that contains the keys of all the key-value pairs.

+
+ + +- Example + + ``` + var searchParamsObject = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing + for (var key of searchParamsObject .keys()) { // Output key-value pairs + console.log(key); + } + ``` + + +### values + +values\(\): IterableIterator + +Obtains an ES6 iterator that contains the values of all the key-value pairs. + +- Return values + + + + + + + + + + +

Type

+

Description

+

IterableIterator<string>

+

ES6 iterator that contains the values of all the key-value pairs.

+
+ + +- Example + + ``` + var searchParams = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing + for (var value of searchParams.values()) { + console.log(value); + } + ``` + + +### \[Symbol.iterator\] + +\[Symbol.iterator\]\(\): IterableIterator<\[string, string\]\> + +Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value, respectively. + +- Return values + + + + + + + + + + +

Type

+

Description

+

IterableIterator<[string, string]>

+

An ES6 iterator.

+
+ + +- Example + + ``` + const paramsObject = new URLSearchParams('fod=bay&edg=bap'); + for (const [name, value] of paramsObject) { + console.log(name, value); + } + ``` + + +### tostring + +toString\(\): string + +Returns search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

String of serialized search parameters, which is percent-encoded if necessary.

+
+ + +- Example + + ``` + let url = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let params = new URLSearchParams(url.search.slice(1)); + params.append('fod', 3); + console.log(params.toString()); + ``` + + +## URL + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

hash

+

string

+

Yes

+

Yes

+

Gets and sets a string that contains a harsh mark (#) followed by the fragment identifier of a URL.

+

host

+

string

+

Yes

+

Yes

+

Gets and sets the host information in a URL.

+

hostname

+

string

+

Yes

+

Yes

+

Gets and sets the hostname (without the port) in a URL.

+

href

+

string

+

Yes

+

Yes

+

Gets and sets a string that contains the whole URL.

+

origin

+

string

+

Yes

+

No

+

Gets a read-only string that contains the Unicode serialization of the origin of the represented URL.

+

password

+

string

+

Yes

+

Yes

+

Gets and sets the password in a URL.

+

pathname

+

string

+

Yes

+

Yes

+

Gets and sets the path in a URL.

+

port

+

string

+

Yes

+

Yes

+

Gets and sets the port in a URL.

+

protocol

+

string

+

Yes

+

Yes

+

Gets and sets the protocol in a URL.

+

search

+

string

+

Yes

+

Yes

+

Gets and sets the serialized query string in a URL.

+

searchParams

+

URLsearchParams

+

Yes

+

No

+

Gets a URLSearchParams object allowing access to the query parameters in a URL.

+

username

+

string

+

Yes

+

Yes

+

Gets and sets the username in a URL.

+
+ +### constructor + +constructor\(url: string, base?: string | URL\) + +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
+
+ + +- Example + + ``` + var mm = 'http://username:password@host:8080'; + var a = new URL("/", mm); // Output 'http://username:password@host:8080/'; + var b = new URL(mm); // Output 'http://username:password@host:8080/'; + new URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; + var c = new URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 + new URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL + new URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL + new URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ + new URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ + ``` + + +### tostring + +toString\(\): string + +Converts the parsed URL into a string. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Website address in a serialized string.

+
+ + +- Example + + ``` + const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + url.toString() + ``` + + +### toJSON + +toJSON\(\): string + +Converts the parsed URL into a JSON string. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Website address in a serialized JSON string.

+
+ + +- Example + + ``` + const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + url.toString() + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md new file mode 100644 index 0000000000000000000000000000000000000000..34e564a8a54a4c9f4c187d00aa5f8c36c3a861c8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -0,0 +1,669 @@ +# String Encoding and Decoding + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import util from '@ohos.util'; +``` + +## Required Permissions + +None + +## util.printf + +printf\(format: string, ...args: Object\[\]\): string + +Prints the input content in a formatted string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

format

+

string

+

Yes

+

Format of the string to print.

+

...args

+

Object[]

+

No

+

Data to format.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

String in the specified format.

+
+ +- Example + + ``` + var res = util.printf("%s", "hello world!"); + console.log(res); + ``` + + +## util.getErrorString + +getErrorString\(errno: number\): string + +Obtains detailed information about a system error code. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

errno

+

number

+

Yes

+

Error code generated.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Detailed information about the error code.

+
+ +- Example + + ``` + var errnum = 10; // 10: a system error number + var result = util.getErrorString(errnum); + console.log("result = " + result); + ``` + + +## util.callbackWrapper + +callbackWrapper\(original: Function\): \(err: Object, value: Object\)=\>void + +Calls back an asynchronous function. In the callback, the first parameter indicates the cause of the rejection \(if the promise has been resolved, the value is **null**\), and the second parameter indicates the resolved value. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

original

+

Function

+

Yes

+

Asynchronous function.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Function

+

Callback, in which the first parameter indicates the cause of the rejection (the value is null if the promise has been resolved) and the second parameter indicates the resolved value.

+
+ +- Example + + ``` + async function promiseFn() { + return Promise.reject('value'); + } + var cb = util.callbackWrapper(promiseFn); + cb((err, ret) => { + expect(err).strictEqual('value'); + expect(ret).strictEqual(undefined); + }) + ``` + + +## util.promiseWrapper + +promiseWrapper\(original: \(err: Object, value: Object\) =\> void\): Object + +Processes an asynchronous function and returns a promise version. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

original

+

Function

+

Yes

+

Asynchronous function to process.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Function

+

Function in the common error-first style (that is, (err, uses value) =>... is used as the last parameter) and the promise version.

+
+ +- Example + + ``` + function aysnFun(str1, str2, callback) { + if (typeof str1 === 'string' && typeof str1 === 'string') { + callback(null, str1 + str2); + } else { + callback('type err'); + } + } + let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); + newPromiseObj.then(res => { + expect(res).strictEqual('HelloWorld'); + }) + ``` + + +## TextDecoder + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

encoding

+

string

+

Yes

+

No

+

Encoding format.

+
  • Supported formats: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrilli, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le
+

fatal

+

boolean

+

Yes

+

No

+

Whether to display fatal errors.

+

ignoreBOM

+

boolean

+

Yes

+

No

+

Whether to ignore the byte order marker (BOM). The default value is false.

+
+ +### constructor + +constructor\(encoding?: string, options?: \{ fatal?: boolean; ignoreBOM?: boolean \},\) + +A constructor used to create a **TextDecoder** instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

encoding

+

string

+

No

+

Encoding format.

+

options

+

Object

+

No

+

Encoding-related options, which include fatal and ignoreBOM.

+
+ + **Table 1** options + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fatal

+

boolean

+

No

+

Whether to display fatal errors.

+

ignoreBOM

+

boolean

+

No

+

Whether to ignore the BOM.

+
+ +- Example + + ``` + var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); + ``` + + +### decode + +decode\(input: Uint8Array, options?:\{stream?:false\}\): string + +Decodes the input parameters and outputs the text. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

Uint8Array

+

Yes

+

Uint8Array to decode.

+

options

+

Object

+

No

+

Options related to decoding.

+
+ + **Table 2** options + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stream

+

boolean

+

No

+

Whether to allow data blocks in the subsequent decode(). Set this parameter to true if data blocks are processed. If data is not divided into blocks or the last data block is processed, set this parameter to false. The default value is false.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Data decoded.

+
+ +- Example + + ``` + var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); + var result = new Uint8Array(6); + result[0] = 0xEF; + result[1] = 0xBB; + result[2] = 0xBF; + result[3] = 0x61; + result[4] = 0x62; + result[5] = 0x63; + console.log("input num:"); + for(var j= 0; j < 6; j++) { + console.log(result[j]); + } + var retStr = textDecoder.decode( result , {stream:false}); + console.log("retStr = " + retStr); + ``` + + +## TextEncoder + +### Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

encoding

+

string

+

Yes

+

No

+

Encoding format. The default value is utf-8.

+
+ +### constructor + +constructor\(\) + +A constructor used to create a **TextEncoder** instance. + +- Example + + ``` + var textEncoder = new util.TextEncoder(); + ``` + + +### encode + +encode\(input?: string\): Uint8Array + +Encodes the input parameter. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

string

+

Yes

+

String to encode.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Encoded text.

+
+ +- Example + + ``` + var textEncoder = new util.TextEncoder(); + var result = new Uint8Array(buffer); + result = textEncoder.encode("\uD800¥¥"); + ``` + + +### encodeInto + +encodeInto\(input: string, dest: Uint8Array,\):\{ read: number; written: number \} + +Stores the UTF-8 encoded text. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

string

+

Yes

+

String to encode.

+

dest

+

Uint8Array

+

Yes

+

Uint8Array instance used to store the UTF-8 encoded text.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Encoded text.

+
+ +- Example + + ``` + var that = new util.TextEncoder(); + var buffer = new ArrayBuffer(4); + this.dest = new Uint8Array(buffer); + var result = that.encodeInto("abcd", this.dest); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..661c24307550feeee1e511d2c9058aa649b2705a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -0,0 +1,413 @@ +# Vibration + +>![](../../public_sys-resources/icon-note.gif) **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 + +``` +import vibrate from '@ohos.vibrator'; +``` + +## Required Permissions + +ohos.permission.VIBRATE + +## vibrate.vibrate + +vibrate\(duration: number\): Promise + +Triggers vibration with a specific duration. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

Yes

+

Vibration duration.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is triggered successfully.

+
+ + +- Example + + ``` + vibrator.vibrate(1000).then(error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Promise returned to indicate a successful vibration."); + } + } + ``` + + +## vibrate.vibrate + +vibrate\(duration: number, callback?: AsyncCallback\): void + +Triggers vibration with a specific duration. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

Yes

+

Vibration duration.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is triggered successfully.

+
+ +- Example + + ``` + vibrator.vibrate(1000,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate a successful vibration."); + } + }) + ``` + + +## vibrate.vibrate + +vibrate\(effectId: EffectId\): Promise + +Triggers vibration with a specific effect. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

effectId

+

EffectId

+

Yes

+

String that indicates the vibration effect.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is triggered successfully.

+
+ + +- Example + + ``` + vibrator.vibrate(effectId:EffectId).then(error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Promise returned to indicate a successful vibration."); + } + } + ``` + + +## vibrate.vibrate + +vibrate\(effectId: EffectId, callback?: AsyncCallback\): void + +Triggers vibration with a specific effect. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

effectId

+

EffectId

+

Yes

+

String that indicates the vibration effect.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is triggered successfully.

+
+ +- Example + + ``` + vibrator.vibrate(effectId:EffectId,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate a successful vibration."); + } + }) + ``` + + +## vibrate.stop + +stop\(stopMode: VibratorStopMode\): Promise + +Stops the vibration based on the specified **stopMode**. This method uses a promise to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stopMode

+

VibratorStopMode

+

Yes

+

Vibration mode to stop.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is stopped successfully.

+
+ + +- Example + + ``` + vibrator.stop(stopMode:VibratorStopMode).then((error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Promise returned to indicate a successful stop."); + } + }) + ``` + + +## vibrate.stop + +stop\(stopMode: VibratorStopMode, callback?: AsyncCallback\): void; + +Stops the vibration based on the specified **stopMode**. This method uses a callback to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stopMode

+

VibratorStopMode

+

Yes

+

Vibration mode to stop.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is stopped successfully.

+
+ +- Example + + ``` + vibrator.stop(stopMode:VibratorStopMode,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Callback returned to indicate a successful stop."); + } + }) + ``` + + +## EffectId + +Describes the vibration effect. + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

EFFECT_CLOCK_TIMER

+

"haptic.clock.timer"

+

Vibration effect of the vibrator when a user adjusts the timer.

+
+ +## VibratorStopMode + +Describes the vibration mode to stop. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

VIBRATOR_STOP_MODE_TIME

+

"time"

+

Indicates that the vibration to stop is in duration mode. This vibration is triggered with the parameter duration of the number type.

+

VIBRATOR_STOP_MODE_PRESET

+

"preset"

+

Indicates the vibration to stop is in EffectId mode. This vibration is triggered with the parameter effectId of the EffectId type.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md new file mode 100644 index 0000000000000000000000000000000000000000..375db98333a6932c3dcde8cce453c5e3f4ef6baa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -0,0 +1,2309 @@ +# Window + +>![](../../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. + +## Modules to Import + +``` +import window from '@ohos.window'; +``` + +## Required Permissions + +ohos.permission.SYSTEM\_FLOAT\_WINDOW + +## SystemBarProperties + +Describes the properties of the status bar and navigation bar. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

statusBarColor

+

string

+

Yes

+

Yes

+

Color of the status bar. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

isStatusBarLightIcon7+

+

boolean

+

Yes

+

Yes

+

Whether any icon on the status bar is highlighted.

+

navigationBarColor

+

string

+

Yes

+

Yes

+

Color of the navigation bar. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

isNavigationBarLightIcon7+

+

boolean

+

Yes

+

Yes

+

Whether any icon on the navigation bar is highlighted.

+
+ +## Rect7+ + +Describes a rectangle. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

left

+

number

+

Yes

+

Yes

+

Left boundary of the rectangle.

+

top

+

number

+

Yes

+

Yes

+

Top boundary of the rectangle.

+

width

+

number

+

Yes

+

Yes

+

Width of the rectangle.

+

height

+

number

+

Yes

+

Yes

+

Height of the rectangle.

+
+ +## AvoidArea7+ + +Describes the area where the window cannot be displayed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

leftRect

+

Rect

+

Yes

+

Yes

+

Rectangle on the left of the screen.

+

topRect

+

Rect

+

Yes

+

Yes

+

Rectangle at the top of the screen.

+

rightRect

+

Rect

+

Yes

+

Yes

+

Rectangle on the right of the screen.

+

bottomRect

+

Rect

+

Yes

+

Yes

+

Rectangle at the bottom of the screen.

+
+ +## Size7+ + +Describes the window size. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

width

+

number

+

Yes

+

Yes

+

Window width.

+

height

+

number

+

Yes

+

Yes

+

Window height.

+
+ +## WindowProperties + +Describes the window properties. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

windowRect7+

+

Rect

+

Yes

+

No

+

Window size.

+

type7+

+

WindowType

+

Yes

+

No

+

Window type.

+

brightness

+

number

+

Yes

+

Yes

+

Screen brightness. The value ranges from 0 to 1. The value 1 indicates the maximum brightness.

+

isTransparent7+

+

boolean

+

Yes

+

Yes

+

Whether the window is transparent. The default value is false.

+

isFullScreen

+

boolean

+

Yes

+

Yes

+

Whether the window is displayed in full screen mode. The default value is false.

+

isKeepScreenOn

+

boolean

+

Yes

+

Yes

+

Whether the screen is always on. The default value is false.

+

dimBehindValue7+

+

number

+

Yes

+

Yes

+

Dimness of the window that is not on top. The value ranges from 0 to 1. The value 1 indicates the maximum dimness.

+

isLayoutFullScreen7+

+

boolean

+

Yes

+

Yes

+

Whether the window layout is in full-screen mode (whether the window is immersive). The default value is false.

+

focusable7+

+

boolean

+

Yes

+

Yes

+

Whether the window can gain focus. The default value is true.

+

touchable7+

+

boolean

+

Yes

+

Yes

+

Whether the window is touchable. The default value is true.

+

isPrivacyMode7+

+

boolean

+

Yes

+

Yes

+

Whether the window is in privacy mode. The default value is false.

+

isRoundCorner7+

+

boolean

+

Yes

+

Yes

+

Whether the window has rounded corners.

+
+ +## SplitScreenBoundsInfo7+ + +Describes information about the split-screen boundary. + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

splitMode7+

+

number

+

Split-screen mode.

+

primaryBounds

+

Rect

+

Primary window boundary information, which is in the format of a Rect instance.

+

secondaryBounds

+

Rect

+

Secondary window boundary information, which is in the format of a Rect instance.

+
+ +## window.getTopWindow + +getTopWindow\(callback: AsyncCallback\): void + +Obtains a **Window** instance. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + + ``` + window.getTopWindow((err, data) => { + if (err) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + windowClass = data; + }); + ``` + + +## window.create7+ + +create\(id: string, type: WindowType, callback: AsyncCallback\): void + +Creates a subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

id

+

string

+

Yes

+

Window ID.

+

type

+

WindowType

+

Yes

+

Window type.

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + +``` + window.create("first", 1, (err, data) => { + windowClass = data; + if (err) { + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('SubWindow created. Data: ' + JSON.stringify(data)) + windowClass.resetSize(500, 1000); + windowClass.setOutsideTouchable(true); + windowClass.loadContent("pages/index/index", (err, data) => { + }); +}) +``` + +## window.find7+ + +find\(id: string, callback: AsyncCallback\): void + +Finds a subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

id

+

string

+

Yes

+

Window ID.

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + + ``` + window.find("first", (err, data) => { + if (err) { + console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('SubWindow found. Data: ' + JSON.stringify(data)) + windowClass = data; + }) + ``` + + +## window.getAbilityWindowMode7+ + +getAbilityWindowMode\(callback: AsyncCallback\): void + +Obtains the mode of this window. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<WindowMode>

+

Yes

+

Callback used to return the window mode.

+
+ +- Example + + ``` + window.getAbilityWindowMode((err, data) => { + if (err) { + console.error(''Failed to obtain the window mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window mode obtained. Data:' + JSON.stringify(data)) + + }); + ``` + + +## window.getSplitScreenBounds7+ + +getSplitScreenBounds\(splitRatio: SplitRatio, callback: AsyncCallback\): void + +Obtains the position and area of multiple windows in split-screen mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

splitRatio

+

SplitRatio

+

Yes

+

Screen split ratio. The default ratio is 1:1. The value 1 indicates the ratio 1:2, and the value 2 indicates the ratio 2:1.

+

callback

+

AsyncCallback<SplitScreenBoundsInfo>

+

Yes

+

Callback used to return a SplitScreenBoundsInfo object that contains the split-screen boundary information.

+
+ +- Example + + ``` + var splitRatio = '1:1'; + window.getSplitScreenBounds(splitRatio, (err, data) => { + if (err) { + console.error('Failed to obtain the split-screen boundary information. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Split-screen boundary information obtained. Data: ' + JSON.stringify(data)) + + }); + ``` + + +## window.isFloatingAbilityWindowVisible7+ + +isFloatingAbilityWindowVisible\(callback:AsyncCallback\): void + +Checks whether the floating window is visible. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to indicate whether the floating window is visible.

+
+ +- Example + + ``` + window.isFloatingAbilityWindowVisible( (err, data) => { + if (err) { + console.error('Failed to check whether the floating window is visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the floating window is visible. Data:' + JSON.stringify(data)) + + }); + ``` + + +## window.setSplitBarVisibility7+ + +setSplitBarVisibility\(isVisibility: boolean, callback: AsyncCallback\): void + +Sets whether the split-screen divider is visible. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

isVisibility

+

boolean

+

Whether to display the divider. The value true means to display the divider, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Callback used to return the execution result.

+
+ +- Example + + ``` + var isVisibility = false; + window.setSplitBarVisibility(isVisibility , (err, data) => { + if (err) { + console.error('Failed to set the divider to be invisible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the divider to be invisible. Data:' + JSON.stringify(data)) + }); + ``` + + +## WindowType7+ + +Window type. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

TYPE_APP

+

0

+

Application window.

+

TYPE_SYSTEM_ALERT

+

1

+

System pop-up window.

+
+ +## AvoidAreaType7+ + +Describes the type of the area where the window cannot be displayed. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

TYPE_SYSTEM

+

0

+

Default area of the system.

+

TYPE_CUTOUT

+

1

+

Notch.

+
+ +## WindowMode7+ + +Describes the window mode of an application. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

UNDEFINED

+

1

+

The window mode is not defined by the application.

+

FULLSCREEN

+

2

+

The application is displayed in full screen.

+

PRIMARY

+

3

+

The application is displayed in the primary window in split-screen mode.

+

SECONDARY

+

4

+

The application is displayed in the secondary window in split-screen mode.

+

FLOATING

+

5

+

The application is displayed in a floating window.

+
+ +## splitMode7+ + +Describes the split-screen mode. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

VERTICAL

+

0

+

Vertical split-screen mode.

+

HORIZONTAL

+

1

+

Horizontal split-screen mode.

+
+ +## Window + +In the following API examples, you must use [getTopWindow\(\)](#section39061940191) to obtain a **Window** instance and then call the corresponding methods based on this instance. + +## setBrightness + +setBrightness\(brightness:number, callback: AsyncCallback\): void + +Sets the brightness for this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

brightness

+

number

+

Yes

+

Brightness to set, which ranges from 0 to 1. The value 1 indicates the brightest.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var brightness = 10; + windowClass.setBrightness(brightness, (err, data) => { + if (err) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setBackgroundColor + +setBackgroundColor\(color: string, callback: AsyncCallback\): void + +Sets the background color for this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

color

+

string

+

Yes

+

Background color to set. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var color = '#00ff33'; + windowClass.setBackgroundColor(color, (err, data) => { + if (err) { + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setTransparent7+ + +setTransparent\(isTransparent: boolean, callback: AsyncCallback\): void + +Sets whether this window is transparent. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isTransparent

+

boolean

+

Yes

+

Whether the window is transparent.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isTransparent = true; + windowClass.setTransparent(isTransparent, (err, data) => { + if (err) { + console.error('Failed to set the window to be transparent. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be transparent. Data: ' + JSON.stringify(data)) + }); + ``` + + +## setFullScreen + +setFullScreen\(isFullScreen: boolean, callback: AsyncCallback\): void + +Sets whether to enable the full-screen mode for this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isFullScreen

+

boolean

+

Yes

+

Whether to enable the full-screen mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isFullScreen = true; + windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err) { + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setKeepScreenOn + +setKeepScreenOn\(isKeepScreenOn: boolean, callback: AsyncCallback\): void + +Sets whether to keep the screen always on. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isKeepScreenOn

+

boolean

+

Yes

+

Whether to keep the screen always on.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isKeepScreenOn = true; + windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { + if (err) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setDimBehind7+ + +setDimBehind\(dimBehindValue: number, callback: AsyncCallback\): void + +Sets the dimness of the window that is not on top. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dimBehindValue

+

number

+

Yes

+

Dimness of the window to set. The value ranges from 0 to 1. The value 1 indicates the dimmest.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.setDimBehind(0.5, (err, data) => { + if (err) { + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); + }); + ``` + + +## setLayoutFullScreen7+ + +setLayoutFullScreen\(isLayoutFullScreen: boolean, callback: AsyncCallback\): void + +Sets whether the window layout is in full-screen mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isLayoutFullScreen

+

boolean

+

Yes

+

Whether the window layout is in full-screen mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isLayoutFullScreen= true; + windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + if (err) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode. Data:' + JSON.stringify(data)); + }); + ``` + + +## setFocusable7+ + +setFocusable\(isFocusable: boolean, callback: AsyncCallback\): void + +Sets whether this window can gain focus. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isFocusable

+

boolean

+

Yes

+

Whether the window can gain focus.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isFocusable= true; + windowClass.setFocusable(isFocusable, (err, data) => { + if (err) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setTouchable7+ + +setTouchable\(isTouchable: boolean, callback: AsyncCallback\): void + +Sets whether this window is touchable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isTouchable

+

boolean

+

Yes

+

Whether the window is touchable.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isTouchable = true; + windowClass.setTouchable(isTouchable, (err, data) => { + if (err) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); + + }); + ``` + + +## setPrivacyMode7+ + +setPrivacyMode\(isPrivacyMode: boolean, callback: AsyncCallback\): void + +Sets whether this window is in privacy mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isPrivacyMode

+

boolean

+

Yes

+

Whether the window is in privacy mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isPrivacyMode = true; + windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { + if (err) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); + + }); + ``` + + +## setSystemBarEnable7+ + +setSystemBarEnable\(names: Array, callback: AsyncCallback\): void + +Sets whether to display the status bar and navigation bar in this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

names

+

Array

+

Yes

+

Whether to display the status bar and navigation bar. For example, to display the status bar and navigation bar, set this parameter to ["status", "navigation"].

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var names = ["status", "navigation"]; + windowClass.setSystemBarEnable(names, (err, data) => { + if (err) { + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setSystemBarProperties + +setSystemBarProperties\(systemBarProperties: SystemBarProperties, callback: AsyncCallback\): void + +Sets the properties of the status bar and navigation bar in this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

SystemBarProperties

+

SystemBarProperties

+

Yes

+

Properties of the status bar and navigation bar to set.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 7. + isStatusBarLightIcon: true, + isNavigationBarLightIcon:false + }; + windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { + if (err) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + }); + ``` + + +## getProperties + +getProperties\(callback: AsyncCallback\): void + +Obtains the properties of this window. This method uses an asynchronous callback to return the window properties. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<WindowProperties>

+

Yes

+

Callback used to return the window properties.

+
+ +- Example + + ``` + windowClass.getProperties((err, data) => { + if (err) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); + }); + ``` + + +## getAvoidArea7+ + +getAvoidArea\(type: AvoidAreaType, callback: AsyncCallback\): void + +Obtains the area where this window cannot be displayed, for example, the system bar area and notch area. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

AvoidAreaType

+

Yes

+

Type of the area. TYPE_SYSTEM indicates the default area of the system. TYPE_CUTOUT indicates the notch area.

+

callback

+

AsyncCallback<AvoidArea>

+

Yes

+

Callback used to return the area.

+
+ +- Example + + ``` + var type = window.AvoidAreaType.TYPE_SYSTEM; + windowClass.getAvoidArea(type, (err, data) => { + if (err) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); + }); + ``` + + +## moveTo7+ + +moveTo\(x: number, y: number, callback: AsyncCallback\): void + +Moves this window. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

x

+

number

+

Yes

+

Distance that the window moves along the x-axis. A positive value indicates that the window moves to the right.

+

y

+

number

+

Yes

+

Distance that the window moves along the y-axis. A positive value indicates that the window moves downwards.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.moveTo(300, 300, (err, data)=>{ + if (err) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window moved. Data:' + JSON.stringify(data)); + + }); + ``` + + +## resetSize7+ + +resetSize\(width: number, height: number, callback: AsyncCallback\): void + +Changes the size of this window. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

width

+

number

+

Yes

+

New width of the window.

+

height

+

number

+

Yes

+

New height of the window.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.resetSize(500, 1000, (err, data) => { + if (err) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window size changed. Data:' + JSON.stringify(data)); + }); + ``` + + +## loadContent7+ + +loadContent\(path: string, callback: AsyncCallback\): void + +Loads content to the subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Path of the page to which the content will be loaded.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.loadContent("pages/page2/page2", (err, data) => { + if (err) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data:' + JSON.stringify(data)); + }); + ``` + + +## hide7+ + +hide \(callback: AsyncCallback\): void + +Hides the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.hide((err, data) => { + if (err) { + console.error('Failed to hide the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Subwindow hidden. Data:' + JSON.stringify(data)) + }) + ``` + + +## show7+ + +show\(callback: AsyncCallback\): void + +Shows the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.show((err, data) => { + if (err) { + console.error('Failed to show the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the subwindow. Data: ' + JSON.stringify(data)) + }) + ``` + + +## isShowing7+ + +isShowing\(callback: AsyncCallback\): void + +Checks whether the subwindow is displayed. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to indicate whether the subwindow is displayed.

+
+ +- Example + + ``` + windowClass.isShowing((err, data) => { + if (err) { + console.error('Failed to check whether the subwindow is showing. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the subwindow is showing. Cause:' + JSON.stringify(data)) + }) + ``` + + +## destroy7+ + +destroy\(callback: AsyncCallback\): void + +Destroys the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.destroy((err, data) => { + if (err) { + console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the subwindow. Data:' + JSON.stringify(data)) + }) + ``` + + +## setOutsideTouchable7+ + +setOutsideTouchable\(touchable: boolean, callback: AsyncCallback\): void; + +Sets whether the area outside the subwindow is touchable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

touchable

+

boolean

+

Yes

+

Whether the area outside the subwindow is touchable. The value true means that such an area is touchable, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.setOutsideTouchable(true, (err, data) => { + if (err) { + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)) + }) + ``` + + +## on\('keyboardHeightChange'\) + +on\(type: string, callback: AsyncCallback\): void + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>This method is deprecated since API version 7. + +Enables listening for keyboard height changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type. Set it to keyboardHeightChange, which indicates listening for keyboard height changes.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the keyboard height.

+
+ +- Example + + ``` + var type= 'keyboardHeightChange'; + windowClass.on(type, (err, data) => { + if (err) { + console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); + }); + ``` + + +## off\('keyboardHeightChange'\) + +off\(type: string, callback?: AsyncCallback\): void + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>This method is deprecated since API version 7. + +Disables listening for keyboard height changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listener type. Set it to keyboardHeightChange, which indicates a listener for keyboard height changes.

+

callback

+

AsyncCallback<number>

+

No

+

Callback used to return the keyboard height.

+
+ +- Example + + ``` + var type= 'keyboardHeightChange'; + windowClass.off(type); + ``` + + +## on\('keyboardHeightChange'|'windowSizeChange'7+|'systemAvoidAreaChange'7+\) + +on\(type: string, callback: Callback\): void; + +Enables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • keyboardHeightChange: listening for keyboard height changes.
  • windowSizeChange7+: listening for window size changes.
  • systemAvoidAreaChange7+: listening for changes to the area where the window cannot be displayed.
+

callback

+

Callback<AvoidArea | Size | number>

+

Yes

+

Callback used to return the information.

+
+ +- Example + + ``` + var type = 'windowSizeChange'; + windowClass.on(type, (data) => { + console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); + }); + ``` + + +## off\('keyboardHeightChange'|'windowSizeChange'7+|'systemAvoidAreaChange'7+\) + +off\(type: string, callback?: Callback\): void; + +Disables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • keyboardHeightChange: listening for keyboard height changes.
  • windowSizeChange7+: listening for window size changes.
  • systemAvoidAreaChange7+: listening for changes to the area where the window cannot be displayed.
+

callback

+

Callback<AvoidArea | Size | number>

+

No

+

Callback used to return the information.

+
+ +- Example + + ``` + var type = 'windowSizeChange'; + windowClass.off(type); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md new file mode 100644 index 0000000000000000000000000000000000000000..ff388df2f05e45d5831d4d72102bdfd6a04ae854 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -0,0 +1,1228 @@ +# Worker Startup + +>![](../../public_sys-resources/icon-note.gif) **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. + +## Modules to Import + +``` +import worker from '@ohos.worker'; +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

parentPort

+

DedicatedWorkerGlobalScope

+

Yes

+

Yes

+

Object of the worker thread used to communicate with the host thread.

+
+ +## WorkerOptions + +Provides options that can be set for the worker to create. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

"classic"

+

Yes

+

Yes

+

Mode in which the worker executes the script.

+

name

+

string

+

Yes

+

Yes

+

Name of the worker.

+
+ +## Worker + +Before using the following methods, you must construct a worker instance. The **worker** class inherits from [EventTarget](#section256019311465). + +### constructor + +constructor\(scriptURL: string, options?: WorkerOptions\) + +A constructor used to create a worker instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

scriptURL

+

string

+

Yes

+

URL of the script to be executed by the worker. The script is stored in the workers directory, which is in the same directory as the pages directory of the new DevEco Studio project. If the workers directory does not exist, you need to create it.

+

options

+

WorkerOptions

+

No

+

Options that can be set for the worker.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

worker

+

Returns the worker instance created; returns undefined if the worker instance fails to be created.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js", {name:"first worker"}); + ``` + + +### postMessage + +postMessage\(message: Object, options?: PostMessageOptions\): void + +Sends a message to the worker thread. The data is transferred using the structured clone algorithm. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

Object

+

Yes

+

Data to be sent to the worker.

+

options

+

PostMessageOptions

+

No

+

ArrayBuffer instances that can be transferred. The transferList array cannot contain null.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.postMessage("hello world"); + + const worker = new worker.Worker("workers/worker.js"); + var buffer = new ArrayBuffer(8); + worker.postMessage(buffer, [buffer]); + ``` + + +### on + +on\(type: string, listener: EventListener\): void + +Adds an event listener to the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.on("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### once + +once\(type: string, listener: EventListener\): void + +Adds an event listener to the worker and removes the event listener automatically after it is invoked once. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.once("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### off + +off\(type: string, listener?: EventListener\): void + +Removes an event listener for the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event for which the event listener is removed.

+

listener

+

EventListener

+

No

+

Callback of the event listener to remove.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.off("alert"); + ``` + + +### terminate + +terminate\(\): void + +Terminates the worker thread to stop the worker from receiving messages. + +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.terminate() + ``` + + +### onexit + +onexit?: \(code: number\) =\> void + +Defines the event handler to be called when the worker exits. The handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

code

+

number

+

No

+

Code indicating the worker exit state.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onexit = function(e) { + console.log("onexit") + } + ``` + + +### onerror + +onerror?: \(err: ErrorEvent\) =\> void + +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

err

+

ErrorEvent

+

No

+

Error data.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onerror = function(e) { + console.log("onerror") + } + ``` + + +### onmessage + +onmessage?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the host thread receives a message created by itself and sent by the worker through the **parentPort.postMessage**. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Message received.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onmessage = function(e) { + console.log("onerror") + } + ``` + + +### onmessageerror + +onmessageerror?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker receives a message that cannot be serialized. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Error data.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onmessageerror= function(e) { + console.log("onmessageerror") + } + ``` + + +## EventTarget + +### addEventListener + +addEventListener\(type: string, listener: EventListener\): void + +Adds an event listener to the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### removeEventListener + +removeEventListener\(type: string, callback?: EventListener\): void + +Removes an event listener for the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event for which the event listener is removed.

+

callback

+

EventListener

+

No

+

Callback of the event listener to remove.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.removeEventListener("alert") + ``` + + +### dispatchEvent + +dispatchEvent\(event: Event\): boolean + +Dispatches the event defined for the worker. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

Event

+

Yes

+

Event to dispatch.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

boolean

+

Returns true if the event is dispatched successfully; returns false otherwise.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.dispatchEvent({type:"alert"}) + ``` + + +### removeAllListener + +removeAllListener\(\): void + +Removes all event listeners for the worker. + +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.removeAllListener({type:"alert"}) + ``` + + +## DedicatedWorkerGlobalScope + +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#section12882825611). + +### postMessage + +postMessage\(message: Object, options?: PostMessageOptions\): void + +Sends a message to the host thread from the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

Object

+

Yes

+

Data to be sent to the worker.

+

options

+

PostMessageOptions

+

No

+

ArrayBuffer instances that can be transferred. The transferList array cannot contain null.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.postMessage("hello world") + worker.onmessage = function(e) { + console.log("receive data from worker.js") + } + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e){ + parentPort.postMessage("receive data from main.js") + } + ``` + + +### close + +close\(\): void + +Closes the worker thread to stop the worker from receiving messages. + +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e) { + parentPort.close() + } + ``` + + +### onmessage + +onmessage?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Message received.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.postMessage("hello world") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e) { + console.log("receive main.js message") + } + ``` + + +### onmessageerror + +onmessageerror?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker receives a message that cannot be deserialized. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Error data.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessageerror= function(e) { + console.log("worker.js onmessageerror") + } + ``` + + +## PostMessageOptions + +Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

transfer

+

Object[]

+

Yes

+

Yes

+

ArrayBuffer array used to transfer the ownership.

+
+ +## Event + +Defines the event. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

string

+

Yes

+

No

+

Type of the event.

+

timeStamp

+

number

+

Yes

+

No

+

Timestamp (accurate to millisecond) when the event is created.

+
+ +## EventListener + +Implements event listening. + +### \(evt: Event\): void | Promise + +Specifies the callback to invoke. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

evt

+

Event

+

Yes

+

Event class for the callback to invoke.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

void | Promise<void>

+

Returns no value or returns a Promise.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +## ErrorEvent + +Provides detailed information about the exception occurred during worker execution. The **ErrorEvent** class inherits from [Event](#section1674694018507). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

message

+

string

+

Yes

+

No

+

Information about the exception.

+

filename

+

string

+

Yes

+

No

+

File where the exception is located.

+

lineno

+

number

+

Yes

+

No

+

Number of the line where the exception is located.

+

colno

+

number

+

Yes

+

No

+

Number of the column where the exception is located.

+

error

+

Object

+

Yes

+

No

+

Type of the exception.

+
+ +## MessageEvent + +Holds the data transferred between worker threads. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

data

+

T

+

Yes

+

No

+

Data transferred between threads.

+
+ +## WorkerGlobalScope + +Defines the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#section256019311465). + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

name

+

string

+

Yes

+

No

+

Worker name specified when there is a new worker.

+

self

+

WorkerGlobalScope & typeof globalThis

+

Yes

+

No

+

WorkerGlobalScope.

+
+ +### onerror + +onerror?: \(ev: ErrorEvent\) =\> void + +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

ev

+

ErrorEvent

+

No

+

Error data.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort + parentPort.onerror = function(e){ + console.log("worker.js onerror") + } + ``` + + diff --git a/en/application-dev/reference/apis/page-routing.md b/en/application-dev/reference/apis/page-routing.md deleted file mode 100644 index 690e16d583d9421555e0d8a9305dd7ef1ef53f17..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/page-routing.md +++ /dev/null @@ -1,306 +0,0 @@ -# Page Routing - -> **NOTICE:** ->Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. - -## Module to Import - -``` -import router from '@system.router'; -``` - -## Permission List - -None - -## router.push\(OBJECT\) - -Navigates to a specified page in the application based on the page URL and parameters. - -- Parameter - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

Yes

-

URI of the destination page, in either of the following formats:

-
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    -
  • Particular path. If the URI is a slash (/), the home page is displayed.
-

params

-

Object

-

No

-

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

-
- -- Example - - ``` - // Example code for the current page - export default { - pushPage() { - router.push({ - uri: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - }, - }, - }); - } - } - // Example code for the routerpage2 page - export default { - data: { - data1: 'default', - data2: { - data3: [1, 2, 3] - } - }, - onInit() { - console.info('showData1:' + this.data1); - console.info('showData3:' + this.data2.data3); - } - } - ``` - - >**NOTE:** - >The page routing stack supports a maximum of 32 pages. - - -## router.replace\(OBJECT\) - -Replaces the current page with another one in the application and destroys the current page. - -- Parameter - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

Yes

-

URI of the destination page, in either of the following formats:

-
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    -
  • Particular path. If the URI is a slash (/), the home page is displayed.
-

params

-

Object

-

No

-

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

-
- -- Example - - ``` - // Example code for the current page - export default { - replacePage() { - router.replace({ - uri: 'pages/detail/detail', - params: { - data1: 'message', - }, - }); - } - } - // Example code for the detail page - export default { - data: { - data1: 'default' - }, - onInit() { - console.info('showData1:' + this.data1) - } - } - ``` - - -## router.back\(OBJECT\) - -Returns to the previous page or a specified page. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

No

-

URI of the page to return to. If the specified page does not exist in the page stack, the app does not respond. If this parameter is not set, the app returns to the previous page.

-
- -- Example - - ``` - // index page - router.push({ - uri: 'pages/detail/detail', - }); - - // detail page - router.push({ - uri: 'pages/mall/mall', - }); - - // Navigate from the mall page to the detail page through router.back(). - router.back(); - // Navigate from the detail page to the index page through router.back(). - router.back(); - // Return to the detail page through router.back(). - router.back({uri:'pages/detail/detail'}); - ``` - - > **NOTE:** - >In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. - - -## router.clear\(\) - -Clears all historical pages and retains only the current page at the top of the stack. - -- Parameter - - N/A - -- Example - - ``` - router.clear(); - ``` - - -## router.getLength\(\) - -Obtains the number of pages in the current stack. - -- Returned Value - - - - - - - - - - -

Type

-

Description

-

string

-

Number of pages in the stack. The maximum value is 32.

-
- -- Example - - ``` - var size = router.getLength(); - console.log('pages stack size = ' + size); - ``` - - -## router.getState\(\) - -Obtains information about the current page state. - -- Returned Value - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

index

-

number

-

Index of the current page in the stack.

-
NOTE:

The index starts from 1 from the bottom to the top of the stack.

-
-

name

-

string

-

Name of the current page, that is, the file name.

-

path

-

string

-

Path of the current page.

-
- -- Example - - ``` - var page = router.getState(); - console.log('current index = ' + page.index); - console.log('current name = ' + page.name); - console.log('current path = ' + page.path); - ``` - - diff --git a/en/application-dev/reference/apis/pop-up-window.md b/en/application-dev/reference/apis/pop-up-window.md deleted file mode 100644 index 0e3c9242de01a535c680a28425412686287ec915..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/pop-up-window.md +++ /dev/null @@ -1,188 +0,0 @@ -# Pop-up Window - -## Module to Import - -``` -import prompt from '@system.prompt'; -``` - -## Permission List - -None - -## prompt.showToast\(OBJECT\) - -Displays the toast dialog box. - -- Parameter - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to display.

-

duration

-

number

-

No

-

Duration of the toast dialog box. The default value is 1500. The recommended value ranges from 1500 ms to 10000 ms.

-
NOTE:

A value less than 1500 is automatically changed to 1500. The maximum value is 10000 ms.

-
-

[bottom]5+

-

<length>

-

No

-

Distance between the dialog border and the bottom of the screen.

-
- -- Example - - ``` - prompt.showToast({ - message: 'Message Info', - duration: 2000, - }); - ``` - - -## prompt.showDialog\(OBJECT\) - -Displays the dialog box. - -- Parameter - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

title

-

string

-

No

-

Title of the text to display.

-

message

-

string

-

No

-

Text body.

-

buttons

-

Array

-

No

-

Array of buttons in the dialog box. The array structure is {text:'button', color: '#666666'}. One to three buttons are supported. The first button is of the positiveButton type, the second is of the negativeButton type, and the third is of the neutralButton type.

-

success

-

Function

-

No

-

Called when the dialog box is displayed. For the return value, see the value that will be returned when the dialog box is displayed.

-

cancel

-

Function

-

No

-

Called when the operation is cancelled.

-

complete

-

Function

-

No

-

Called when the dialog box is closed.

-
- - The following value will be returned when the dialog box is displayed. - - - - - - - - - - - - -

Parameter

-

Type

-

Description

-

index

-

number

-

Index of the selected button in the buttons array

-
- -- Example - - ``` - prompt.showDialog({ - title: 'Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button', - color: '#666666', - }, - ], - success: function(data) { - console.log('dialog success callback,click button : ' + data.index); - }, - cancel: function() { - console.log('dialog cancel callback'); - }, - }); - ``` - - diff --git a/en/application-dev/reference/apis/resource-management.md b/en/application-dev/reference/apis/resource-management.md deleted file mode 100644 index 9c6ed7962d665a010e068e22531c2876d567a7b0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/resource-management.md +++ /dev/null @@ -1,1079 +0,0 @@ -# Resource Management - - -## Imported Modules - -``` -import resmgr from '@ohos.resmgr'; -``` - -## Permissions - -None. - -## Methods - -## getResourceManager - -Obtains the **ResourceManager** object of the current application. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<ResourceManager>

-

Yes

-

Indicates the callback containing the ResourceManager object.

-
- -**Return Values** - -None. - -**Example** - -``` -resmgr.getResourceManager((error, mgr) => { - // callback - mgr.getString(0x1000000, (error, value) => { - if (error != null) { - console.log(value); - } else { - console.log(value); - } - }); - - // promise - mgr.getString(0x1000000).then(value => { - console.log(value); - }).catch(error => { - console.log("getstring promise " + error); - }); -} - -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the specified application. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Indicates the bundle name of the specified application.

-

callback

-

AsyncCallback<ResourceManager>

-

Yes

-

Indicates the callback containing the ResourceManager object.

-
- -**Return Values** - -None. - -**Example** - -``` -resmgr.getResourceManager("com.example.myapplication", (error, mgr) => { -} -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the current application. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<ResourceManager>

-

Indicates that the ResourceManager object is returned in Promise mode.

-
- -**Example** - -``` -resmgr.getResourceManager().then(mgr => { - // callback - mgr.getString(0x1000000, (error, value) => { - if (error != null) { - console.log(value); - } else { - console.log(value); - } - }); - - // promise - mgr.getString(0x1000000).then(value => { - console.log(value); - }).catch(error => { - console.log("getstring promise " + error); - }); -}).catch(error => { - -}); -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the specified application. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Indicates the bundle name of the specified application.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<ResourceManager>

-

Indicates that the ResourceManager object is returned in Promise mode.

-
- -**Example** - -``` -resmgr.getResourceManager("com.example.myapplication").then(mgr => { - -}).catch(error => { - -}); -``` - -## Enum - -## Direction - -Enumerates screen directions - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

DIRECTION_VERTICAL

-

0

-

Indicates the vertical direction.

-

DIRECTION_HORIZONTAL

-

1

-

Indicates the horizontal direction.

-
- -## DeviceType - -Enumerates device types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

DEVICE_TYPE_PHONE

-

0x00

-

Indicates a phone.

-

DEVICE_TYPE_TABLET

-

0x01

-

Indicates a tablet.

-

DEVICE_TYPE_CAR

-

0x02

-

Indicates a head unit.

-

DEVICE_TYPE_PC

-

0x03

-

Indicates a PC.

-

DEVICE_TYPE_TV

-

0x04

-

Indicates a smart TV.

-

DEVICE_TYPE_WEARABLE

-

0x06

-

Indicates a wearable.

-
- -## ScreenDensity - -Enumerates screen density types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SCREEN_SDPI

-

120

-

Indicates small screen density.

-

SCREEN_MDPI

-

160

-

Indicates medium screen density.

-

SCREEN_LDPI

-

240

-

Indicates large screen density.

-

SCREEN_XLDPI

-

320

-

Indicates extra-large screen density.

-

SCREEN_XXLDPI

-

480

-

Indicates extra-extra-large screen density.

-

SCREEN_XXXLDPI

-

640

-

Indicates extra-extra-extra-large screen density.

-
- -## Appendix - -## AsyncCallback - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Mandatory

-

Description

-

error

-

Error

-

No

-

Returns an error if an exception is thrown during execution; returns an empty value otherwise.

-

data

-

T

-

No

-

Returns a T object if the execution is successful; returns an empty value otherwise.

-
- -## Configuration - -Provides the device configuration. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Readable

-

Writable

-

Description

-

direction

-

Direction

-

Yes

-

No

-

Indicates the screen direction of the current device.

-

locale

-

string

-

Yes

-

No

-

Indicates the current system language, for example, zh-Hans-CN.

-
- -## DeviceCapability - -Provides the device capability. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Readable

-

Writable

-

Description

-

screenDensity

-

ScreenDensity

-

Yes

-

No

-

Indicates the screen density of the current device.

-

deviceType

-

DeviceType

-

Yes

-

No

-

Indicates the type of the current device.

-
- -## ResourceManager - -Provides the capability of accessing application resources. - -### getString - -Obtains the character string corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the obtained character string.

-
- -**Return Values** - -None. - -### getString - -Obtains string resources associated with a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the character string corresponding to the resource ID.

-
- -### getStringArray - -Obtains the array of character strings corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<Array<string>>

-

Yes

-

Indicates the asynchronous callback used to return the obtained array of character strings.

-
- -**Return Values** - -None. - -### getStringArray - -Obtains the array of character strings corresponding to a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Array<string>>

-

Indicates the array of character strings corresponding to the specified resource ID.

-
- -### getMedia - -Obtains the content of the media file corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<Array<Uint8Array>>

-

Yes

-

Indicates the asynchronous callback used to return the obtained media file content.

-
- -**Return Values** - -None. - -### getMedia - -Obtains the content of the media file corresponding to a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Array<Uint8Array>>

-

Indicates the content of the media file corresponding to the specified resource ID.

-
- -### getMediaBase64 - -Obtains the Base64 code of the image resource corresponding to the specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the obtained Base64 code of the image resource.

-
- -**Return Values** - -None. - -### getMediaBase64 - -Obtains the Base64 code of the image resource corresponding to the specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the Base64 code of the image resource corresponding to the specified resource ID.

-
- -### getConfiguration - -Obtains the device configuration in callback mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<Configuration>

-

Yes

-

Indicates the asynchronous callback used to return the obtained device configuration.

-
- -**Return Values** - -None. - -### getConfiguration - -Obtains the device configuration in Promise mode. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Configuration>

-

Indicates the device configuration.

-
- -### getDeviceCapability - -Obtains the device capability in callback mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<DeviceCapability>

-

Yes

-

Indicates the asynchronous callback used to return the obtained device capability.

-
- -**Return Values** - -None. - -### getDeviceCapability - -Obtains the device capability in Promise mode. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<DeviceCapability>

-

Indicates the device capability.

-
- -**Return Values** - -None. - -### getPluralString - -Obtains the singular-plural character string represented by the ID string corresponding to the specified number in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

num:

-

number

-

Yes

-

Indicates the number.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the singular-plural character string represented by the ID string corresponding to the specified number.

-
- -**Return Values** - -None. - -### getPluralString - -Obtains the singular-plural character string represented by the ID string corresponding to the specified number in Promise mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

num:

-

number

-

Yes

-

Indicates the number.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the singular-plural character string represented by the ID string corresponding to the specified number.

-
- diff --git a/en/application-dev/reference/apis/screen-brightness.md b/en/application-dev/reference/apis/screen-brightness.md deleted file mode 100644 index f1ad6c94e78b6e2ede49f8ca2e53767c7ca841d3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/screen-brightness.md +++ /dev/null @@ -1,51 +0,0 @@ -# Screen Brightness - -## Modules to Import - -``` -import brightness from '@ohos.brightness.d.ts'. -``` - -## Functions - -## setValue\(value: number\) - -Sets the screen brightness. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

value

-

number

-

Yes

-

Brightness value, ranging from 0 to 255

-
- -**Return Values** - -None - -- Example - - ``` - import brightness from '@ohos.brightness.d.ts' - brightness.setValue(128); - ``` - - diff --git a/en/application-dev/reference/apis/system-attribute.md b/en/application-dev/reference/apis/system-attribute.md deleted file mode 100644 index d4d681bb83bad7eeb937e9b1404457b94f90ddbb..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/system-attribute.md +++ /dev/null @@ -1,462 +0,0 @@ -# System Attribute - -## Modules to Import - -``` -import parameter from '@ohos.systemparameter' -``` - -## Required Permissions - -None - -## Functions - -## getSync\(key: string, def?: string\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

string

-

System attribute value. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.

-
- -**Example** - -``` -try { - var info = parameter.getSync("test.parameter.key"); - console.log(JSON.stringify(info)); -}catch(e){ - console.log("getSync unexpected error: " + e); -} -``` - -## get\(key: string, callback: AsyncCallback\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

callback

-

AsyncCallback<string>

-

Yes

-

Callback function

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.get("test.parameter.key", function (err, data) { - if (err == undefined) { - console.log("get test.parameter.key value success:" + data) - } else { - console.log(" get test.parameter.key value err:" + err.code) - }}); -}catch(e){ - console.log("get unexpected error: " + e); -} -``` - -## get\(key: string, def: string, callback: AsyncCallback\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

Yes

-

Default value

-

callback

-

AsyncCallback<string>

-

Yes

-

Callback function

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.get("test.parameter.key", "default", function (err, data) { - if (err == undefined) { - console.log("get test.parameter.key value success:" + data) - } else { - console.log(" get test.parameter.key value err:" + err.code) - } - }); -}catch(e){ - console.log("get unexpected error:" + e) -} -``` - -## get\(key: string, def?: string\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Promise, which is used to obtain the result asynchronously

-
- -**Example** - -``` -try { - var p = parameter.get("test.parameter.key"); - p.then(function (value) { - console.log("get test.parameter.key success: " + value); - }).catch(function (err) { - console.log("get test.parameter.key error: " + err.code); - }); -}catch(e){ - console.log("get unexpected error: " + e); -} -``` - -## setSync\(key: string, value: string\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

value

-

string

-

Yes

-

System attribute value to set

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.setSync("test.parameter.key", "default"); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - -## set\(key: string, value: string, callback: AsyncCallback\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

Yes

-

Default value

-

callback

-

AsyncCallback<void>

-

Yes

-

Callback function.

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.set("test.parameter.key", "testValue", function (err, data) { - if (err == undefined) { - console.log("set test.parameter.key value success :" + data) - } else { - console.log("set test.parameter.key value err:" + err.code) - }}); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - -## set\(key: string, def?: string\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Promise, which is used to obtain the result asynchronously

-
- -**Example** - -``` -try { - var p = para.set("test.parameter.key", "testValue"); - p.then(function (value) { - console.log("set test.parameter.key success: " + value); - }).catch(function (err) { - console.log(" set test.parameter.key error: " + err.code); - }); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - diff --git a/en/application-dev/reference/apis/timer.md b/en/application-dev/reference/apis/timer.md deleted file mode 100644 index 59a115942ccbf825c05be15a63ba998df4b27bdb..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/timer.md +++ /dev/null @@ -1,210 +0,0 @@ -# Timer - -## Module to Import - -None - -## Permission List - -None - -## setTimeout\(handler\[, delay\[, ...args\]\]\) - -Sets a timer for the system to call a function after the timer goes off. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called after the timer goes off.

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution. If this parameter is left empty, the default value 0 is used, which means that the execution starts immediately or as soon as possible.

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off.

-
- -- Return Value - - **timeoutID**: timer ID - -- Example - - ``` - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); - ``` - - -## clearTimeout\(timeoutID\) - -Cancels the timer created via **setTimeout\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

timeoutID

-

number

-

Yes

-

ID of the timer to cancel, which is returned by setTimeout()

-
- -- Example - - ``` - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - - clearTimeout(timeoutID); - ``` - - -## setInterval\(handler\[, delay\[, ...args\]\]\) - -Sets a repeating timer for the system to repeatedly call a function at a fixed interval. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called repeatedly

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off

-
- -- Return Value - - **intervalID**: ID of the repeating timer - -- Example - - ``` - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - ``` - - -## clearInterval\(intervalID\) - -Cancels the repeating timer set via **setInterval\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

intervalID

-

number

-

Yes

-

ID of the repeating timer to cancel, which is returned by setInterval().

-
- -- Example - - ``` - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - - clearInterval(intervalID); - ``` - - diff --git a/en/application-dev/reference/apis/updater.md b/en/application-dev/reference/apis/updater.md deleted file mode 100644 index fbb89fa2c86d4a548c66f72f1357cd15aac32e01..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/updater.md +++ /dev/null @@ -1,313 +0,0 @@ -# Updater - -## Modules to Import - -``` -import client from 'libupdateclient.z.so' -``` - -## Required Permissions - -None - -## updater.getNewVersionInfo\(\) - -Obtains new version information. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

No

-

AsyncCallback<NewVersionInfo>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

info

-

NewVersionInfo

-

New version information

-
- -**Example** - -``` -updater.getNewVersionInfo(info => { -console.log("getNewVersionInfo success " + info.status); -console.log(`info versionName = ` + info.result[0].versionName); -console.log(`info versionCode = ` + info.result[0].versionCode); -console.log(`info verifyInfo = ` + info.result[0].verifyInfo); -)}; -``` - -## updater.checkNewVersion\(\) - -Checks for a new version. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

No

-

AsyncCallback<NewVersionInfo>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

info

-

NewVersionInfo

-

New version information

-
- -**Example** - -``` -updater.checkNewVersion(info => { -console.log("checkNewVersion success " + info.status); -console.log(`info versionName = ` + info.result[0].versionName); -console.log(`info versionCode = ` + info.result[0].versionCode); -console.log(`info verifyInfo = ` + info.result[0].verifyInfo); -)}; -``` - -## updater.download\(\) - -Downloads the new version and displays the download process. - -**Parameters** - -None - -**Return Values** - -None - -**Example** - -``` -updater.on("downloadProgress", progress => { -console.log("downloadProgress on" + progress); -console.log(`downloadProgress status: ` + progress.status); -console.log(`downloadProgress percent: ` + progress.percent); -)}; -updater.download(); -``` - -## updater.upgrade\(\) - -Starts an update. - -**Parameters** - -None - -**Return Values** - -None - -**Example** - -``` -updater.on("upgradeProgress", progress => { -console.log("downloadProgress on" + progress); -console.log(`downloadProgress status: ` + progress.status); -console.log(`downloadProgress percent: ` + progress.percent); -)}; -updater.upgrade(); -``` - -## updater.setUpdatePolicy\(\) - -Sets the update policy. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

policy

-

UpdatePolicy

-

Yes

-

Update policy

-

callback

-

Function

-

Yes

-

AsyncCallback<number>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

result

-

number

-
  
- -**Example** - -``` -// Set the update policy. -let policy = { -autoDownload: false, -autoDownloadNet: true, -mode: 2, -autoUpgradeInterval: [ 2, 3 ], -autoUpgradeCondition: 2 -} -updater.setUpdatePolicy(policy, function(result) { -console.log("setUpdatePolicy ", result) -} -); -``` - -## updater.getUpdatePolicy\(\) - -Checks the update policy. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

Yes

-

AsyncCallback<UpdatePolicy>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

policy

-

UpdatePolicy

-

Update policy

-
- -**Example** - -``` -updater.getUpdatePolicy(policy => { -console.log("getUpdatePolicy success", policy) -}); -``` - diff --git a/zh-cn/application-dev/reference/apis/js-apis.md b/zh-cn/application-dev/reference/apis/js-apis.md deleted file mode 100644 index 995d83c72f0404cec907c2b95b545325a7589e09..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis.md +++ /dev/null @@ -1,21 +0,0 @@ -# 接口 - - - -- **[Ability框架](js-apis-ability.md)** - -- **[资源管理](js-apis-resource.md)** - -- **[媒体](js-apis-multmedia.md)** - -- **[数据管理](js-apis-data.md)** - -- **[账号管理](js-apis-account.md)** - -- **[电话服务](js-apis-telephony.md)** - -- **[设备管理](js-apis-device-mgmt.md)** - -- **[基本功能](js-apis-basic-features.md)** - -- **[语言基础类库](js-apis-base-library.md)** \ No newline at end of file