diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 48270359d9d49f9ea7d7111b021cd8b81da3df82..3bafb0bc097f0277f88ff4489c2731afdad6569e 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -92,7 +92,7 @@ After the preceding code is executed, the **startAbility()** API is called to st - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. -The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications). +The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). ```javascript import featureAbility from '@ohos.ability.featureAbility'; diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 4c293fdee7114866ebd969151c0914d29a144941..62bf66fd7cabb7e30c765126ddacba639bd951f5 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -9,15 +9,15 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | +| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | +| ohos.i18n | getSystemRegion(): string | Obtains the system region. | +| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | +| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | +| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | +| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | +| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | ### How to Develop @@ -26,7 +26,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). - + ```js var language = i18n.getSystemLanguage(); ``` @@ -42,7 +42,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Obtain the system locale. Call the **getSystemLocale** method to obtain the system locale. - + ```js var locale = i18n.getSystemLocale(); ``` @@ -51,7 +51,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **isRTL** method to check whether the locale's language is RTL. - + ```js var rtl = i18n.isRTL("zh-CN"); ``` @@ -67,7 +67,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Obtain the localized display of a language. Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var language = "en"; var locale = "zh-CN"; @@ -78,7 +78,7 @@ You can use APIs provided in the following table to obtain the system language a 7. Obtain the localized display of a country. Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var country = "US"; var locale = "zh-CN"; @@ -116,7 +116,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - + ```js var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` @@ -135,7 +135,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Set the year, month, day, hour, minute, and second for the **Calendar** object. Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` @@ -144,7 +144,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. - + ```js calendar.setTimeZone("Asia/Shanghai"); var timezone = calendar.getTimeZone(); @@ -163,7 +163,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Set and obtain the minimum count of days in the first week for the **Calendar** object. Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - + ```js calendar.setMinimalDaysInFirstWeek(3); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); @@ -173,7 +173,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. - + ```js var localizedName = calendar.getDisplayName("zh-CN"); ``` @@ -196,11 +196,11 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | +| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | +| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | ### How to Develop @@ -209,7 +209,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. - + ```js var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); ``` @@ -223,7 +223,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Format a phone number. Call the **format** method of **PhoneNumberFormat** to format the input phone number. - + ```js var formattedNumber = phoneNumberFormat.format("15812341234"); ``` @@ -236,15 +236,15 @@ The **unitConvert** API is provided to help you implement measurement conversion ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | +| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | ### How to Develop 1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. + Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. ```js @@ -254,7 +254,7 @@ The **unitConvert** API is provided to help you implement measurement conversion var locale = "en-US"; var style = "long"; i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ``` ## Alphabet Index @@ -278,7 +278,7 @@ The **unitConvert** API is provided to help you implement measurement conversion Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - + ```js var indexUtil = i18n.getInstance("zh-CN"); ``` @@ -294,7 +294,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 3. Add an index. Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - + ```js indexUtil.addLocale("ar") ``` @@ -302,7 +302,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 4. Obtain the index of a string. Call the **getIndex** method to obtain the alphabet index of a string. - + ```js var text = "access index"; indexUtil.getIndex(text); @@ -336,7 +336,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **getLineInstance** method to instantiate a **BreakIterator** object. - + ```js var locale = "en-US" var breakIterator = i18n.getLineInstance(locale); @@ -357,7 +357,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. - + ```js var pos = breakIterator.current(); ``` @@ -383,7 +383,9 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. - + ```js var isboundary = breakIterator.isBoundary(5); ``` + + ``` \ No newline at end of file diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 424320dcc17f3dc0eb6d3e30970869da83874408..540e8dbf89029df9daa4825c5883eb7d41271412 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -13,13 +13,13 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | +| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | +| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | +| ohos.intl | toString(): string | Converts locale information into a string. | +| ohos.intl | maximize(): Locale | Maximizes locale information. | +| ohos.intl | minimize(): Locale | Minimizes locale information. | ### How to Develop @@ -81,13 +81,13 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to f ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | ### How to Develop @@ -144,12 +144,12 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to forma ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | +| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | +| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | ### How to Develop @@ -195,12 +195,12 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | +| ohos.intl | constructor()8+ | Creates a **Collator** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | +| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | +| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | ### How to Develop @@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). ```js var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); @@ -246,11 +246,11 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | +| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | ### How to Develop @@ -264,7 +264,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). ```js var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -287,13 +287,13 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | ### How to Develop @@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). ```js var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md index d1d7416500d37ab61523633f3880670ad8b98779..39f44f65437b6b91ce457228fa12153d10aed3e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md @@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions'; | Name| Readable| Writable| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.| +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | Yes| No| number | No| Window mode.| | displayId | Yes| No| number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 135400833c36005e1504b32f56f353cd2f271e40..2d7e9fab8a62e7d68dae92e66359a2704414bc01 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,6 +1,7 @@ # Battery Info ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE** +> >The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. @@ -25,7 +26,7 @@ Describes battery information. | batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | | healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggertype) | Yes | No | Charger type of the current device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | | voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | | technology | string | Yes | No | Battery technology of the current device. | | batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | @@ -43,12 +44,12 @@ var batterySoc = batteryInfo.batterySOC; Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ---------------- | -| NONE | 0 | Unknown type | -| AC | 1 | AC charger | -| USB | 2 | USB charger | -| WIRELESS | 3 | Wireless charger | +| Name | Default Value | Description | +| -------- | ------------- | ----------------- | +| NONE | 0 | Unknown type. | +| AC | 1 | AC charger. | +| USB | 2 | USB charger. | +| WIRELESS | 3 | Wireless charger. | ## BatteryChargeState diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 3c908fabdc24cccc6f5949c9d5add8da88a08d01..b998d06bc0ca9900249144012f30e1230a0598f1 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -500,6 +500,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| **Example** + ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 5b9107af6a142f762171272278e3ea543bb93b81..7df95d23175b36a0e4aefa65ea0b04c1862a2c94 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -22,720 +22,888 @@ A sensor is a device to detect events or changes in an environment and send mess import sensor from '@ohos.sensor'; ``` -## sensor.on +## sensor.on9+ -### ACCELEROMETER +### ACCELEROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void +on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELERATIONdeprecated +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### ACCELEROMETER_UNCALIBRATED9+ -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. +on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>,options?: Options): void -This API is deprecated since API version 9. You are advised to use **Sensor.on.LINEAR_ACCELEROMETER9+** instead. +Subscribes to data of the uncalibrated acceleration sensor. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### LINEAR_ACCELEROMETER9+ +```js +try { + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>, options?: Options): void +### AMBIENT_LIGHT9+ -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. +on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` -### ACCELEROMETER_UNCALIBRATED +```js +try { + sensor.on(sensor.SensorId.AMBIENT_LIGHT,function(data){ + console.info('Illumination: ' + data.intensity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void +### AMBIENT_TEMPERATURE9+ -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. +on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` -### GRAVITY +```js +try { + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### BAROMETER9+ -on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void +on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, options?: Options): void -Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + +```js +try { + sensor.on(sensor.SensorId.BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### GRAVITY9+ + +on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data of the gravity sensor. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.on(sensor.SensorId.GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE +### GYROSCOPE9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options?: Options): void -Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GYROSCOPE_UNCALIBRATED +### GYROSCOPE_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void +on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>, + 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. +Subscribes to data of the uncalibrated gyroscope sensor. -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +**Required permissions**: ohos.permission.GYROSCOPE -**System capability**: SystemCapability.Sensors.Sensor +**System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### SIGNIFICANT_MOTION +### HALL9+ -on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void +on(type: SensorId.HALL, callback: Callback<HallResponse>, 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. +Subscribes to data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER_DETECTION +```js +try { + sensor.on(sensor.SensorId.HALL,function(data){ + console.info('Status: ' + data.status); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void +### HEART_RATE9+ -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. +on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the heart rate sensor. + +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | Callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, - {interval: 10000000} - ); - ``` -### PEDOMETER +```js +try { + sensor.on(sensor.SensorId.HEART_RATE,function(data){ + console.info('Heart rate: ' + data.heartRate); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void +### HUMIDITY9+ -Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. +on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, - {interval: 10000000} - ); - ``` -### AMBIENT_TEMPERATURE +```js +try { + sensor.on(sensor.SensorId.HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void +### LINEAR_ACCELERATION9+ -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. +on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>, + options?: Options): void + +Subscribes to data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, - {interval: 10000000} - ); - ``` -### MAGNETIC_FIELD +```js +try { + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### MAGNETIC_FIELD9+ -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void +on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,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. +Subscribes to data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### MAGNETIC_FIELD_UNCALIBRATED +### MAGNETIC_FIELD_UNCALIBRATED9+ -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void +on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>, 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. +Subscribes to data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + +```js +try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### PROXIMITY +### ORIENTATION9+ -on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void +on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,options?: Options): void -Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, - {interval: 10000000} - ); - ``` -### HUMIDITY - -on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void +```js +try { + sensor.on(sensor.SensorId.ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. +### PEDOMETER9+ -**System capability**: SystemCapability.Sensors.Sensor +on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +Subscribes to data of the pedometer sensor. -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, - {interval: 10000000} - ); - ``` +**Required permissions**: ohos.permission.ACTIVITY_MOTION -### BAROMETER +**System capability**: SystemCapability.Sensors.Sensor -on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void +**Error code** -Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**System capability**: SystemCapability.Sensors.Sensor +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, - {interval: 10000000} - ); - ``` -### HALL +```js +try { + sensor.on(sensor.SensorId.PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void +### PEDOMETER_DETECTION9+ -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. +on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, + options?: Options): void -**System capability**: SystemCapability.Sensors.Sensor +Subscribe to data of the pedometer detection sensor. -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +**Required permissions**: ohos.permission.ACTIVITY_MOTION -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ - console.info('Status: ' + data.status); - }, - {interval: 10000000} - ); - ``` +**System capability**: SystemCapability.Sensors.Sensor -### AMBIENT_LIGHT +**Parameters** -on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -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. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ - console.info(' Illumination: ' + data.intensity); - }, - {interval: 10000000} - ); - ``` -### ORIENTATION +```js +try { + sensor.on(sensor.SensorId.PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### PROXIMITY9+ -on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void +on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, options?: Options): void -Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, - {interval: 10000000} - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -### HEART_RATEdeprecated +**Error code** -on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the heart rate sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.on(sensor.SensorId.PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -This API is deprecated since API version 9. You are advised to use **sensor.on.HEART_BEAT_RATE9+** instead. +### ROTATION_VECTOR9+ -**Required permissions**: ohos.permission.READ_HEALTH_DATA +on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>, + options?: Options): void + +Subscribes to data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### HEART_BEAT_RATE9+ - -on(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>, options?: Options): void +### SIGNIFICANT_MOTION9+ -Subscribes to only one data change of the heart rate sensor. +on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, + options?: Options): void -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Subscribes to data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); +try { + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -### ROTATION_VECTOR +### WEAR_DETECTION9+ -on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void +on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>, + options?: Options): void -Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. +Subscribes to data of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | - -**Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, - {interval: 10000000} - ); - ``` -### WEAR_DETECTION +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void - -Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + +```js +try { + sensor.on(sensor.SensorId.WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); - }, - {interval: 10000000} - ); - ``` + }, {interval: 10000000} ); +} catch(err) { + console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## sensor.once +## sensor.once9+ -### ACCELEROMETER +### ACCELEROMETER9+ -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>): void -Subscribes to only one data change of the acceleration sensor. +Subscribes to data of the acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` - -### LINEAR_ACCELERATIONdeprecated - -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void - -Subscribes to only one data change of the linear acceleration sensor. -This API is deprecated since API version 9. You are advised to use **sensor.once.LINEAR_ACCELEROMETER9+** instead. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### LINEAR_ACCELEROMETER9+ +### ACCELEROMETER_UNCALIBRATED9+ -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<LinearAccelerometerResponse>): void +once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void -Subscribes to only one data change of the linear acceleration sensor. +Subscribes to data of the uncalibrated acceleration sensor once. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### ACCELEROMETER_UNCALIBRATED - -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void - -Subscribes to only one data change of the uncalibrated acceleration sensor. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ``` - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + +```js +try { + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); @@ -744,1649 +912,2107 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -### GRAVITY +### AMBIENT_LIGHT9+ -once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void +once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): void -Subscribes to only one data change of the gravity sensor. +Subscribes to data of the ambient light sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE +```js +try { + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function(data) { + console.info('Illumination: ' + data.intensity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void +### AMBIENT_TEMPERATURE9+ -Subscribes to only one data change of the gyroscope sensor. +once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the ambient temperature sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` -### GYROSCOPE_UNCALIBRATED +```js +try { + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void +### BAROMETER9+ -Subscribes to only one data change of the uncalibrated gyroscope sensor. +once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the barometer sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -### SIGNIFICANT_MOTION +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the significant motion sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` - -### PEDOMETER_DETECTION +```js +try { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void +### GRAVITY9+ -Subscribes to only one data change of the pedometer detection sensor. +once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Subscribes to data of the gravity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); - ``` - -### PEDOMETER +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void +**Error code** -Subscribes to only one data change of the pedometer sensor. +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Required permissions**: ohos.permission.ACTIVITY_MOTION +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +```js +try { + sensor.once(sensor.SensorId.GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); - ``` +### GYROSCOPE9+ -### AMBIENT_TEMPERATURE +once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void +Subscribes to data of the gyroscope sensor once. -Subscribes to only one data change of the ambient temperature sensor. +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -### MAGNETIC_FIELD +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the magnetic field sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` +### GYROSCOPE_UNCALIBRATED9+ -### MAGNETIC_FIELD_UNCALIBRATED +once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void +Subscribes to data of the uncalibrated gyroscope sensor once. -Subscribes to only one data change of the uncalibrated magnetic field sensor. +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); - ``` - -### PROXIMITY -once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -Subscribes to only one data change of the proximity sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); - ``` -### HUMIDITY +```js +try { + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### HALL9+ -once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void +once(type: SensorId.HALL, callback: Callback<HallResponse>): void -Subscribes to only one data change of the humidity sensor. +Subscribes to data of the Hall effect sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { - console.info('Humidity: ' + data.humidity); - } - ); - ``` +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -### BAROMETER +**Error code** -once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Subscribes to only one data change of the barometer sensor. +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -**System capability**: SystemCapability.Sensors.Sensor +**Example** -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +```js +try { + sensor.once(sensor.SensorId.HALL, function(data) { + console.info('Status: ' + data.status); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); - ``` +### HEART_RATE9+ -### HALL +once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): void -once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void +Subscribes to data of the heart rate sensor once. -Subscribes to only one data change of the Hall effect sensor. +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { - console.info('Status: ' + data.status); - } - ); - ``` - -### AMBIENT_LIGHT -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -Subscribes to only one data change of the ambient light sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { - console.info(' Illumination: ' + data.intensity); - } - ); - ``` -### ORIENTATION +```js +try { + sensor.once(sensor.SensorId.HEART_BEAT_RATE, function(data) { + console.info('Heart rate: ' + data.heartRate); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void +### HUMIDITY9+ -Subscribes to only one data change of the orientation sensor. +once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to data of the humidity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); - ``` - -### ROTATION_VECTOR -once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -Subscribes to only one data change of the rotation vector sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); - ``` -### HEART_RATEdeprecated +```js +try { + sensor.once(sensor.SensorId.HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void +### LINEAR_ACCELERATION9+ -Subscribes to only one data change of the heart rate sensor. +once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void -This API is deprecated since API version 9. You are advised to use **sensor.once.HEART_BEAT_RATE9+** instead. +Subscribes to data of the linear acceleration sensor once. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` -### HEART_BEAT_RATE9+ +```js +try { + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -once(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback: Callback<HeartRateResponse>): void +### MAGNETIC_FIELD9+ -Subscribes to only one data change of the heart rate sensor. +once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void -**Required permissions**: ohos.permission.READ_HEALTH_DATA +Subscribes to data of the magnetic field sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| - -**Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` -### WEAR_DETECTION +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void - -Subscribes to only one data change of the wear detection sensor. +**Error code** -**System capability**: SystemCapability.Sensors.Sensor +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -**Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); - ``` - -## sensor.off -### ACCELEROMETER +```js +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void +### MAGNETIC_FIELD_UNCALIBRATED9+ -Unsubscribes from sensor data changes. +once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the uncalibrated magnetic field sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -### ACCELEROMETER_UNCALIBRATED - -off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void +### ORIENTATION9+ -Unsubscribes from sensor data changes. +once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Subscribes to data of the orientation sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + sensor.once(sensor.SensorId.ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -### AMBIENT_LIGHT +### PEDOMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void +once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the pedometer sensor once. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Example** +**Error code** -```js -function callback(data) { - console.info(' Illumination: ' + data.intensity); -} -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); -``` - -### AMBIENT_TEMPERATURE - -off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). -Unsubscribes from sensor data changes. - -**System capability**: SystemCapability.Sensors.Sensor - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Temperature: ' + data.temperature); +try { + sensor.once(sensor.SensorId.PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -### AMBIENT_TEMPERATURE +### PEDOMETER_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void +once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>): void -Unsubscribes from sensor data changes. +Subscribe to data of the pedometer detection sensor once. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**.| -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); +try { + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -### GRAVITY +### PROXIMITY9+ -off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void +once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the proximity sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -### GYROSCOPE - -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void +### ROTATION_VECTOR9+ -Unsubscribes from sensor data changes. +once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the rotation vector sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**.| -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -### GYROSCOPE_UNCALIBRATED - -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void +### SIGNIFICANT_MOTION9+ -Unsubscribes from sensor data changes. +once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>): void -**Required permissions**: ohos.permission.GYROSCOPE (a system permission) +Subscribes to data of the significant motion sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -### HALL +### WEAR_DETECTION9+ -off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void +once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -Unsubscribes from sensor data changes. +Subscribes to data of the wear detection sensor once. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to subscribe to, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +**Error code** + +For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -function callback(data) { - console.info('Status: ' + data.status); +try { + sensor.once(sensor.SensorId.WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); +} catch(err) { + console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -### HEART_RATEdeprecated +## sensor.off9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void +### ACCELEROMETER9+ -Unsubscribes from sensor data changes. +off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void -This API is deprecated since API version 9. You are advised to use **sensor.off.HEART_BEAT_RATE9+** instead. +Unsubscribes from data of the acceleration sensor. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -### HEART_BEAT_RATE9+ +### ACCELEROMETER_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback?: Callback<HeartRateResponse>): void +off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated acceleration sensor. -**Required permissions**: ohos.permission.READ_HEALTH_DATA +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**.| -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); ``` -### HUMIDITY +### AMBIENT_LIGHT9+ -off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void +off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| **Example** ```js -function callback(data) { - console.info('Humidity: ' + data.humidity); +try { + function callback(data) { + console.info('Illumination: ' + data.intensity); + } + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -### LINEAR_ACCELERATIONdeprecated - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void - -Unsubscribes from sensor data changes. +### AMBIENT_TEMPERATURE9+ -This API is deprecated since API version 9. You are advised to use **sensor.off.LINEAR_ACCELEROMETER9+** instead. +off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Unsubscribes from data of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('Temperature: ' + data.temperature); + } + sensor.off( sensor.SensorId.AMBIENT_TEMPERATURE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -### LINEAR_ACCELEROMETER9+ - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void +### BAROMETER9+ -Unsubscribes from sensor data changes. +off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): void -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) +Unsubscribes from data of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + sensor.off(sensor.SensorId.BAROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); ``` -### MAGNETIC_FIELD +### GRAVITY9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void +off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the gravity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| -| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off( sensor.SensorId.GRAVITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -### MAGNETIC_FIELD_UNCALIBRATED +### GYROSCOPE9+ - off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void +off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -### ORIENTATION +### GYROSCOPE_UNCALIBRATED9+ - off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void +off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void -Unsubscribes from sensor data changes. + Unsubscribes from data of the uncalibrated gyroscope sensor. + +**Required permissions**: ohos.permission.GYROSCOPE **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**.| -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** ```js -function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -### PEDOMETER - -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void +### HALL9+ -Unsubscribes from sensor data changes. +off(type: SensorId.HALL, callback?: Callback<HallResponse>): void -**Required permissions**: ohos.permission.ACTIVITY_MOTION +Unsubscribes from data of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** ```js -function callback(data) { - console.info('Steps: ' + data.steps); +try { + function callback(data) { + console.info('Status: ' + data.status); + } + sensor.off(sensor.SensorId.HALL, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -### PEDOMETER_DETECTION +### HEART_RATE9+ -off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void +off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the heart rate sensor. -**Required permissions**: ohos.permission.ACTIVITY_MOTION +**Required permissions**: ohos.permission.READ_HEALTH_DATA **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info("Heart rate: " + data.heartRate); + } + sensor.off(sensor.SensorId.HEART_RATE, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -### PROXIMITY +### HUMIDITY9+ -off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void +off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**.| -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** ```js -function callback(data) { - console.info('Distance: ' + data.distance); +try { + function callback(data) { + console.info('Humidity: ' + data.humidity); + } + sensor.off(sensor.SensorId.HUMIDITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -### ROTATION_VECTOR +### LINEAR_ACCELEROMETER9+ -off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void +off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerometerResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELEROMETER **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** ```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -### SIGNIFICANT_MOTION +### MAGNETIC_FIELD9+ -off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void +off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** ```js -function callback(data) { - console.info('Scalar data: ' + data.scalar); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -### WEAR_DETECTION +### MAGNETIC_FIELD_UNCALIBRATED9+ -off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void -Unsubscribes from sensor data changes. +Unsubscribes from data of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** ```js -function accCallback(data) { - console.info('Wear status: ' + data.value); +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); ``` -## sensor.transformCoordinateSystem +### ORIENTATION9+ -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void +off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): void -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | ----------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** ```js -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { - if (err) { - console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Operation successed. Data obtained: " + data); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); +try { + function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); } - }) + sensor.off(sensor.SensorId.ORIENTATION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.transformCoordinateSystem -transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> +### PEDOMETER9+ -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. +off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): void -**System capability**: SystemCapability.Sensors.Sensor +Unsubscribes from data of the pedometer sensor. -**Parameters** +**Required permissions**: ohos.permission.ACTIVITY_MOTION -| Name | Type | Mandatory | Description | -| ---------------- | ---------------------------------------- | ---- | -------- | -| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| +**System capability**: SystemCapability.Sensors.Sensor -**Return value** +**Parameters** -| Type | Description | -| ---------------------------------- | ----------- | -| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** ```js -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); - promise.then((data) => { - console.info("Operation successed."); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }).catch((err) => { - console.info("Operation failed"); -}) +try { + function callback(data) { + console.info('Steps: ' + data.steps); + } + sensor.off(sensor.SensorId.PEDOMETER, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.getGeomagneticField +### PEDOMETER_DETECTION9+ -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void +off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the pedometer detection sensor. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** + ```js -sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); } - console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); -}); + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## sensor.getGeomagneticField -getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> +### PROXIMITY9+ -Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. +off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from data of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ----------------------------------- | ---- | ----------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -**Return value** -| Type | Description | -| ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** - ```js - const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); - promise.then((data) => { - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }).catch((reason) => { - console.info('Operation failed.'); - }) - ``` -## sensor.getAltitude +```js +try { + function callback(data) { + console.info('Distance: ' + data.distance); + } + sensor.off(sensor.SensorId.PROXIMITY, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +### ROTATION_VECTOR9+ -getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void +off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. +Unsubscribes from data of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | ---- | -------------------- | -| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | -| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| -| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| **Example** - ```js - sensor.getAltitude(0, 200, function(err, data) { - if (err) { - console.error( - "Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Successed to get getAltitude interface get data: " + data); - }); - ``` +```js +try { + function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## sensor.getAltitude +### SIGNIFICANT_MOTION9+ -getAltitude(seaPressure: number, currentPressure: number): Promise<number> +off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. +Unsubscribes from data of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ------ | ---- | -------------------- | -| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | -| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -**Return value** +**Example** -| Type | Description | -| --------------------- | ------------------ | -| Promise<number> | Promise used to return the altitude, in meters.| +```js +try { + function callback(data) { + console.info('Scalar data: ' + data.scalar); + } + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -**Example** +### WEAR_DETECTION9+ - ```js - const promise = sensor.getAltitude(0, 200); - promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data); - }).catch((err) => { - console.error("Operation failed"); - }) - ``` +off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void +Unsubscribes from data of the wear detection sensor. -## sensor.getGeomagneticDip +**System capability**: SystemCapability.Sensors.Sensor -getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void +**Parameters** -Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorId](#sensorid9) | Yes | Type of the sensor to unsubscribe from, which is **WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| + +**Example** + +```js +try { + function accCallback(data) { + console.info('Wear status: ' + data.value); + } + sensor.off(sensor.SensorId.WEAR_DETECTION, accCallback); +} catch(err) { + console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` + +## sensor.getGeomagneticInfo9+ + +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void + +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------------- | --------------------------- | ---- | -------------- | -| inclinationMatrix | Array<number> | Yes | Inclination matrix. | -| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + - err.message); - return; - } - console.info("Successed to get getGeomagneticDip interface get data: " + data); - }) - ``` +```js +try { + sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000, function(data) { + console.info('sensor_getGeomagneticInfo_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }); +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getGeomagneticDip +## sensor.getGeomagneticInfo9+ -getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> +getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> -Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------------- | ------------------- | ---- | ------- | -| inclinationMatrix | Array<number> | Yes | Inclination matrix.| +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------- | ---- | ---------------------------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| **Return value** -| Type | Description | -| --------------------- | -------------- | -| Promise<number> | Promise used to return the magnetic dip, in radians.| +| Type | Description | +| ---------------------------------------------------------- | -------------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getGeomagneticInfo](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { - console.info('getGeomagneticDip_promise successed', data); - }).catch((err) => { - console.error("Operation failed"); + console.info('sensor_getGeomagneticInfo_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }).catch((reason) => { + console.info('Operation failed.'); }) - ``` +} catch (err) { + console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor. getAngleModify +## sensor.getDeviceAltitude9+ -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void +getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------------- | ---------------------------------------- | ---- | ------------------ | -| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | -| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| +| Name | Type | Mandatory| Description | +| --------------- | --------------------------- | ---- | ------------------------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -**Example** +**Error code** - ```js - sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { - if (err) { - console.error('Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) - ``` +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | -## sensor. getAngleModify +**Example** -getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> +```js +try { + sensor.getDeviceAltitude(0, 200, function(data) { + console.info('Successed to get getDeviceAltitude interface get data: ' + data); + }); +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -Obtains the angle change between two rotation matrices. This API uses a promise to return the result. +## sensor.getDeviceAltitude9+ + +getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<number> + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------------- | ------------------- | ---- | --------- | -| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| -| preRotationMatrix | Array<number> | Yes | Rotation matrix. | +| Name | Type | Mandatory| Description | +| --------------- | ------ | ---- | ------------------------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| +| Type | Description | +| --------------------- | ------------------------------------ | +| Promise<number> | Promise used to return the altitude, in meters.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getDeviceAltitude](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); +```js +try { + const promise = sensor.getDeviceAltitude (0, 200); promise.then((data) => { - console.info('getAngleModifiy_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); + console.info('sensor_getDeviceAltitude_Promise success', data); + }).catch((err) => { + console.error("Operation failed"); }) - ``` - +} catch (err) { + console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getInclination9+ -createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void +getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory| Description | +| ----------------- | --------------------------- | ---- | ---------------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } +```js +try { + sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info('Successed to get getInclination interface get data: ' + data); }) - ``` - +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createRotationMatrix +## sensor.getInclination9+ -createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> + getInclination(inclinationMatrix: Array<number>): Promise<number> -Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| ----------------- | ------------------- | ---- | -------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix.| **Return value** -| Type | Description | -| ---------------------------------- | ------- | -| Promise<Array<number>> | Promise used to return the rotation matrix.| +| Type | Description | +| --------------------- | ---------------------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getInclination](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); +```js +try { + const promise = sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info('createRotationMatrix_promise success'); - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }).catch((reason) => { - console.info("promise::catch", reason); - }) - ``` - + console.info('getInclination_promise successed', data); + }).catch((err) => { + console.error("Operation failed"); + }) +} catch (err) { + console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createQuaternion +## sensor.getAngleVariation9+ -createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, + callback: AsyncCallback): void -Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | +| Name | Type | Mandatory| Description | +| --------------------- | ---------------------------------------- | ---- | --------------------------------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } +```js +try { + sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(data) { for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.createQuaternion +## sensor.getAngleVariation9+ -createQuaternion(rotationVector: Array<number>): Promise<Array<number>> +getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise -Converts a rotation vector into a quaternion. This API uses a promise to return the result. +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory| Description | +| --------------------- | ------------------- | ---- | ------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<Array<number>> | Promise used to return the quaternion.| +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getAngleVariation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); +```js +try { + const promise = sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info('createQuaternion_promise successed'); for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info('promise failed'); + }).catch((reason) => { + console.info('promise::catch ', reason); }) - ``` - +} catch (err) { + console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getDirection +## sensor.getRotationMatrix9+ -getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void +getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void -Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. +Obtains the rotation matrix from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------- | ---- | ------------------ | -| rotationMatrix | Array<number> | Yes | Rotation matrix. | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; - } - console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_callback" + data[i]); +```js +try { + sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } }) - ``` - +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getDirection +## sensor.getRotationMatrix9+ -getDirection(rotationMatrix: Array<number>): Promise<Array<number>> +getRotationMatrix(rotationVector: Array<number>): Promise -Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. +Obtains the rotation matrix from a rotation vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------- | ---- | ------- | -| rotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | -------------- | +| Promise<Array<number>> | Promise used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); +```js +try { + const promise = sensor.getRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info('sensor_getAltitude_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info("sensor_getDirection_promise" + data[i]); + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info('promise failed'); + }).catch((reason) => { + console.info('promise::catch ', reason); }) - ``` +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` +## sensor.transformRotationMatrix9+ -## sensor.createRotationMatrix +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, + callback: AsyncCallback): void -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(data) { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.transformRotationMatrix9+ + +transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ----------------------------------------- | ---- | ---------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------------- | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.transformRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + for (var i=0; i < data.length; i++) { + console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) +} catch (err) { + console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getQuaternion9+ + +getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void + +Obtains the quaternion from a rotation vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ------- | -| gravity | Array<number> | Yes | Gravity vector.| -| geomagnetic | Array<number> | Yes | Geomagnetic vector.| -| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** - ```js - sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { - if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + - err.message); - return; +```js +try { + sensor.getQuaternion ([0.20046076, 0.21907, 0.73978853, 0.60376877], function(data) { + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]) + }) +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getQuaternion9+ + +getQuaternion(rotationVector: Array<number>): Promise + +Obtains the quaternion from a rotation vector. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationVector | Array<number> | Yes | Rotation vector.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------ | +| Promise<Array<number>> | Callback used to return the quaternion.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getQuaternion](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.getQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('getQuaternionn_promise successed'); + for (var i=0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) +} catch (err) { + console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getOrientation9+ + +getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void + +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | --------------------------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { + console.info("SensorJsAPI--->Successed to get getOrientation interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_callback ' + data[i]); } }) - ``` +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` +## sensor.getOrientation9+ -## sensor.createRotationMatrix +getOrientation(rotationMatrix: Array<number>): Promise -createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | -------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix.| + +**Return value** + +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getOrientation](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + const promise = sensor.getOrientation([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('sensor_getOrientation_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info('sensor_getOrientation_promise ' + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getRotationMatrix9+ + +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void + +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + +**Example** + +```js +try { + sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(data) { + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); + }) +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` + +## sensor.getRotationMatrix9+ + +getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Obtains the rotation matrix based on a gravity vector and geomagnetic vector. This API uses a promise to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | ------- | -| gravity | Array<number> | Yes | Gravity vector.| -| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| Name | Type | Mandatory| Description | +| ----------- | ------------------- | ---- | -------------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| **Return value** -| Type | Description | -| ---------------------------------------- | ------- | +| Type | Description | +| ------------------------------------------------------------ | -------------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getRotationMatrix](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | + **Example** - ```js - const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); +```js +try { + const promise = sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { - console.info('createRotationMatrix_promise successed'); - for (var i=0; i < data.rotation.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } + console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); }).catch((err) => { console.info('promise failed'); }) - ``` +} catch (err) { + console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); +} +``` -## sensor.getSensorLists9+ +## sensor.getSensorList9+ - getSensorLists(callback: AsyncCallback): void + getSensorList(callback: AsyncCallback): void Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. @@ -2394,28 +3020,36 @@ Obtains information about all sensors on the device. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | Yes | Callback used to return the sensor list.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback | Yes | Callback used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSensorList((error, data) => { - if (error) { - console.error('getSensorList failed'); - } else { - console.info("getSensorList callback in" + data.length); +try { + sensor.getSensorList((data) => { + console.info('getSensorList callback in ' + data.length); for (var i = 0; i < data.length; i++) { console.info("getSensorList " + JSON.stringify(data[i])); } - } -}); + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## sensor.getSensorLists9+ +## sensor.getSensorList9+ - getSensorLists(): Promise< Array<Sensor>> + getSensorList(): Promise< Array<Sensor>> Obtains information about all sensors on the device. This API uses a promise to return the result. @@ -2423,26 +3057,38 @@ Obtains information about all sensors on the device. This API uses a promise to **Return value** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------------- | ---- | ---------------- | -| promise | Promise | Yes | Promise used to return the sensor list.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ---------------- | +| promise | Promise | Yes | Promise used to return the sensor list.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSensorList](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSensorList().then((data) => { - console.info("getSensorList promise in" + data.length); - for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); - } -}, (error)=>{ - console.error('getSensorList failed'); -}); +try { + sensor.getSensorList().then((data) => { + console.info('getSensorList promise in ' + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } + }, (error)=>{ + console.error('getSensorList failed'); + }); +} catch (err) { + console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ -getSingleSensor(type: SensorType, callback: AsyncCallback<sensor>): void +getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void Obtains information about the sensor of a specific type. This API uses an asynchronous callback to return the result. @@ -2450,26 +3096,34 @@ Obtains information about the sensor of a specific type. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------- | -| type | SensorType | Yes | Sensor type. | -| callback | AsyncCallback<[Sensor](#sensor)> | Yes | Callback used to return the sensor information.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------------- | +| type | [SensorId](#sensorid9) | Yes | Sensor type. | +| callback | AsyncCallback<[Sensor](#sensor9)> | Yes | Callback used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js - sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { - if (error) { - console.error('getSingleSensor failed'); - } else { - console.info("getSingleSensor " + JSON.stringify(data)); - } -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { + console.info('getSingleSensor ' + JSON.stringify(data)); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` ## sensor.getSingleSensor9+ - getSingleSensor(type: SensorType,): Promise<Sensor> + getSingleSensor(type: SensorId): Promise<Sensor> Obtains information about the sensor of a specific type. This API uses a promise to return the result. @@ -2477,58 +3131,98 @@ Obtains information about the sensor of a specific type. This API uses a promise **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------ | -| type | SensorType | Yes | Sensor type.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------ | +| type | [SensorId](#sensorid9) | Yes | Sensor type.| **Return value** -| Name | Type | Mandatory| Description | -| ------- | -------------------------------- | ---- | ---------------- | -| promise | Promise<[Sensor](#sensor)> | Yes | Promise used to return the sensor information.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------- | ---- | ---------------- | +| promise | Promise<[Sensor](#sensor9)> | Yes | Promise used to return the sensor information.| + +**Error code** + +For details about the following error codes, see [Error Codes of sensor.getSingleSensor](../errorcodes/errorcode-sensor.md). + +| Error Code ID| Error Message | +| -------- | ------------------ | +| 14500101 | Service exception. | **Example** ```js -sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { - console.info("getSingleSensor " + JSON.stringify(data)); -}, (error)=>{ - console.error('getSingleSensor failed'); -}); +try { + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { + console.info('getSingleSensor '+ JSON.stringify(data)); + }, (error)=>{ + console.error('getSingleSensor failed'); + }); +} catch (err) { + console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); +} ``` -## SensorType +## SensorId9+ + +Enumerates the sensor types. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Default Value| Description | +| --------------------------- | ------ | ---------------------- | +| ACCELEROMETER | 1 | Acceleration sensor. | +| GYROSCOPE | 2 | Gyroscope sensor. | +| AMBIENT_LIGHT | 5 | Ambient light sensor. | +| MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| BAROMETER | 8 | Barometer sensor. | +| HALL | 10 | Hall effect sensor. | +| PROXIMITY | 12 | Proximity sensor. | +| HUMIDITY | 13 | Humidity sensor. | +| ORIENTATION | 256 | Orientation sensor. | +| GRAVITY | 257 | Gravity sensor. | +| LINEAR_ACCELEROMETER | 258 | Linear acceleration sensor. | +| ROTATION_VECTOR | 259 | Rotation vector sensor. | +| AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| PEDOMETER | 266 | Pedometer sensor. | +| HEART_RATE | 278 | Heart rate sensor. | +| WEAR_DETECTION | 280 | Wear detection sensor. | +| ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| + +## SensorType(deprecated) Enumerates the sensor types. **System capability**: SystemCapability.Sensors.Sensor -| 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_ACCELERATIONdeprecated | 258 | Linear acceleration sensor. | -| SENSOR_TYPE_ID_LINEAR_ACCELEROMETER | 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_RATEdeprecated | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_HEART_BEAT_RATE | 278 | Heart rate sensor. | -| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | -| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| +| 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.| ## Response @@ -2541,7 +3235,7 @@ Describes the timestamp of the sensor data. | --------- | -------- | ---- | ---- | ------------------------ | | timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| -## Sensor +## Sensor9+ Describes the sensor information. @@ -2553,8 +3247,10 @@ Describes the sensor information. | venderName | string | Vendor of the sensor. | | firmwareVersion | string | Firmware version of the sensor. | | hardwareVersion | string | Hardware version of the sensor. | -| sensorTypeId | number | Sensor type ID. | +| sensorId | number | Sensor type ID. | | maxRange | number | Maximum measurement range of the sensor.| +| minSamplePeriod | number | Minimum sampling period. | +| maxSamplePeriod | number | Maximum sampling period. | | precision | number | Precision of the sensor. | | power | number | Power supply of the sensor. | @@ -2565,11 +3261,11 @@ Describes the acceleration sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ------------------------------------ | +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| ## LinearAccelerometerResponse @@ -2579,11 +3275,11 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| ## AccelerometerUncalibratedResponse @@ -2593,14 +3289,14 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------------- | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | ## GravityResponse @@ -2610,11 +3306,11 @@ Describes the gravity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------------------- | +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| ## OrientationResponse @@ -2624,11 +3320,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ----------------- | -| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | --------------------------------- | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse @@ -2638,12 +3334,12 @@ Describes the rotation vector sensor data. It extends from [Response](#response) **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | --------- | -| x | number | Yes | Yes | X-component of the rotation vector.| -| y | number | Yes | Yes | Y-component of the rotation vector.| -| z | number | Yes | Yes | Z-component of the rotation vector.| -| w | number | Yes | Yes | Scalar. | +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------------- | +| x | number | Yes | Yes | X-component of the rotation vector.| +| y | number | Yes | Yes | Y-component of the rotation vector.| +| z | number | Yes | Yes | Z-component of the rotation vector.| +| w | number | Yes | Yes | Scalar. | ## GyroscopeResponse @@ -2653,11 +3349,11 @@ Describes the gyroscope sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------------------- | -| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| -| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| -| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | -------------------------------- | +| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| +| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| +| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| ## GyroscopeUncalibratedResponse @@ -2667,14 +3363,14 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | -| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | -| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | -| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | -| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| -| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| -| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------ | +| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | +| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | +| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | +| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| +| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| +| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| ## SignificantMotionResponse @@ -2684,9 +3380,9 @@ Describes the significant motion sensor data. It extends from [Response](#respon **System capability**: SystemCapability.Sensors.Sensor -| 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.| +| 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 @@ -2696,9 +3392,9 @@ Describes the proximity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| 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.| +| 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 @@ -2708,9 +3404,9 @@ Describes the ambient light sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----------- | -| intensity | number | Yes | Yes | Illumination, in lux.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------------------- | +| intensity | number | Yes | Yes | Illumination, in lux.| ## HallResponse @@ -2746,14 +3442,14 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ---------------------- | -| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | -| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | -| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | -| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| -| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| -| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | -------------------------------------- | +| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | +| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| +| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| +| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| ## PedometerResponse @@ -2763,9 +3459,9 @@ Describes the pedometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | -------- | -| steps | number | Yes | Yes | Number of steps a user has walked.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ---------------- | +| steps | number | Yes | Yes | Number of steps a user has walked.| ## HumidityResponse @@ -2775,9 +3471,9 @@ Describes the humidity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------------------------------ | -| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | --------------------------------------------------------- | +| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| ## PedometerDetectionResponse @@ -2787,9 +3483,9 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| 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.| +| 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 @@ -2799,9 +3495,9 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------------- | -| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | -------------------------- | +| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| ## BarometerResponse @@ -2811,9 +3507,9 @@ Describes the barometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| -------- | ------ | ---- | ---- | ------------ | -| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------------ | +| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| ## HeartRateResponse @@ -2823,9 +3519,9 @@ Describes the heart rate sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | --------------------- | -| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | --------------------------------------- | +| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| ## WearDetectionResponse @@ -2835,9 +3531,9 @@ Describes the wear detection sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------- | -| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ----- | -------- | ---- | ---- | ------------------------------------------------ | +| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| ## Options @@ -2846,9 +3542,9 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Description | -| -------- | ------ | --------------------------- | -| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| +| Name | Type| Description | +| -------- | -------- | ------------------------------------------- | +| interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| ## RotationMatrixResponse @@ -2856,10 +3552,10 @@ Describes the response for setting the rotation matrix. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----------- | ------------------- | ---- | ---- | ----- | -| rotation | Array<number> | Yes | Yes | Rotation matrix.| -| inclination | Array<number> | Yes | Yes | Inclination matrix.| +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------- | ---- | ---- | ---------- | +| rotation | Array<number> | Yes | Yes | Rotation matrix.| +| inclination | Array<number> | Yes | Yes | Inclination matrix.| ## CoordinatesOptions @@ -2868,10 +3564,10 @@ Describes the coordinate options. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ---- | ------ | ---- | ---- | ------ | -| x | number | Yes | Yes | X coordinate direction.| -| y | number | Yes | Yes | Y coordinate direction.| +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ----------- | +| x | number | Yes | Yes | X coordinate direction.| +| y | number | Yes | Yes | Y coordinate direction.| ## GeomagneticResponse @@ -2880,15 +3576,15 @@ Describes a geomagnetic response object. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------------- | ------ | ---- | ---- | ------------------------- | -| x | number | Yes | Yes | North component of the geomagnetic field. | -| y | number | Yes | Yes | East component of the geomagnetic field. | -| z | number | Yes | Yes | Vertical component of the geomagnetic field. | -| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | -| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| -| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | -| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | +| Name | Type| Readable| Writable| Description | +| --------------- | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | Yes | Yes | North component of the geomagnetic field. | +| y | number | Yes | Yes | East component of the geomagnetic field. | +| z | number | Yes | Yes | Vertical component of the geomagnetic field. | +| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | +| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| +| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | +| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | ## LocationOptions @@ -2896,8 +3592,2607 @@ Describes the geographical location. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ----- | -| latitude | number | Yes | Yes | Latitude. | -| longitude | number | Yes | Yes | Longitude. | -| altitude | number | Yes | Yes | Altitude.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ---------- | +| latitude | number | Yes | Yes | Latitude. | +| longitude | number | Yes | Yes | Longitude. | +| altitude | number | Yes | Yes | Altitude.| + +## sensor.on(deprecated) + +### ACCELEROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void + +Subscribes to data changes of the acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER](#accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### LINEAR_ACCELERATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +### LINEAR_ACCELEROMETER9+ + +on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, + 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. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### GRAVITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void + +Subscribes to data changes of the gravity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GRAVITY](#gravity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void + +Subscribes to data changes of the gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE](#gyroscope9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + ``` + +### SIGNIFICANT_MOTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.SIGNIFICANT_MOTION](#significant_motion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER_DETECTION](#pedometer_detection9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ + console.info('Scalar data: ' + data.scalar); + }, + {interval: 10000000} + ); + ``` + +### PEDOMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void + +Subscribes to data changes of the pedometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PEDOMETER](#pedometer9) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ + console.info('Steps: ' + data.steps); + }, + {interval: 10000000} + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_TEMPERATURE](#ambient_temperature9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ + console.info('Temperature: ' + data.temperature); + }, + {interval: 10000000} + ); + + ``` + +### MAGNETIC_FIELD(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD](#magnetic_field9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, + {interval: 10000000} + ); + + ``` + +### PROXIMITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void + +Subscribes to data changes of the proximity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.PROXIMITY](#proximity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ + console.info('Distance: ' + data.distance); + }, + {interval: 10000000} + ); + + ``` + +### HUMIDITY(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void + +Subscribes to data changes of the humidity sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HUMIDITY](#humidity9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ + console.info('Humidity: ' + data.humidity); + }, + {interval: 10000000} + ); + + ``` + +### BAROMETER(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void + +Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.BAROMETER](#barometer9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ + console.info('Atmospheric pressure: ' + data.pressure); + }, + {interval: 10000000} + ); + + ``` + +### HALL(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HALL](#hall9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ + console.info('Status: ' + data.status); + }, + {interval: 10000000} + ); + + ``` + +### AMBIENT_LIGHT(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, 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. + +This API is deprecated since API version 9. You are advised to use [sensor.on.AMBIENT_LIGHT](#ambient_light9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ + console.info(' Illumination: ' + data.intensity); + }, + {interval: 10000000} + ); + ``` + +### ORIENTATION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void + +Subscribes to data changes of the orientation sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ORIENTATION](#orientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }, + {interval: 10000000} + ); + + ``` + +### HEART_RATE(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, + options?: Options): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + +```js +sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ + console.info("Heart rate: " + data.heartRate); +}, + {interval: 10000000} +); + +``` + +### ROTATION_VECTOR(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void + +Subscribes to data changes of the rotation vector sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.ROTATION_VECTOR](#rotation_vector9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, + {interval: 10000000} + ); + ``` + +### WEAR_DETECTION(deprecated) + +on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void + +Subscribes to data changes of the wear detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +This API is deprecated since API version 9. You are advised to use [sensor.on.WEAR_DETECTION](#wear_detection9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | + +**Example** + + ```js + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ + console.info('Wear status: ' + data.value); + }, + {interval: 10000000} + ); + + ``` + +## sensor.once(deprecated) + +### ACCELEROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void + +Subscribes to only one data change of the acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER](#accelerometer9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### LINEAR_ACCELERATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void + +Subscribes to only one data change of the linear acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELERATION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +### LINEAR_ACCELEROMETER9+ + +once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void + +Subscribes to only one data change of the linear acceleration sensor. + +**Required permissions**: ohos.permission.ACCELERATION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated acceleration sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#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(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### GRAVITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void + +Subscribes to only one data change of the gravity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GRAVITY](#gravity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### GYROSCOPE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void + +Subscribes to only one data change of the gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE](#gyroscope9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated gyroscope sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-1) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### SIGNIFICANT_MOTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void + +Subscribes to only one data change of the significant motion sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.SIGNIFICANT_MOTION](#significant_motion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + + ``` + +### PEDOMETER_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void + +Subscribes to only one data change of the pedometer detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER_DETECTION](#pedometer_detection9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { + console.info('Scalar data: ' + data.scalar); + } + ); + + ``` + +### PEDOMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void + +Subscribes to only one data change of the pedometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PEDOMETER](#pedometer9-1) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { + console.info('Steps: ' + data.steps); + } + ); + ``` + +### AMBIENT_TEMPERATURE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void + +Subscribes to only one data change of the ambient temperature sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_TEMPERATURE](#ambient_temperature9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { + console.info('Temperature: ' + data.temperature); + } + ); + + ``` + +### MAGNETIC_FIELD(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void + +Subscribes to only one data change of the magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD](#magnetic_field9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + + ``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void + +Subscribes to only one data change of the uncalibrated magnetic field sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + + ``` + +### PROXIMITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void + +Subscribes to only one data change of the proximity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.PROXIMITY](#proximity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { + console.info('Distance: ' + data.distance); + } + ); + ``` + +### HUMIDITY(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void + +Subscribes to only one data change of the humidity sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HUMIDITY](#humidity9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { + console.info('Humidity: ' + data.humidity); + } + ); + + ``` + +### BAROMETER(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void + +Subscribes to only one data change of the barometer sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.BAROMETER](#barometer9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + + ``` + +### HALL(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void + +Subscribes to only one data change of the Hall effect sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HALL](#hall9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { + console.info('Status: ' + data.status); + } + ); + + ``` + +### AMBIENT_LIGHT(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void + +Subscribes to only one data change of the ambient light sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.AMBIENT_LIGHT](#ambient_light9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { + console.info(' Illumination: ' + data.intensity); + } + ); + + ``` + +### ORIENTATION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void + +Subscribes to only one data change of the orientation sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ORIENTATION](#orientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + } + ); + + ``` + +### ROTATION_VECTOR(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void + +Subscribes to only one data change of the rotation vector sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.ROTATION_VECTOR](#rotation_vector9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + } + ); + + ``` + +### HEART_RATE(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEART_RATE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void + +Subscribes to only one data change of the heart rate sensor. + +**Required permissions**: ohos.permission.HEART_RATE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { + console.info("Heart rate: " + data.heartRate); + } + ); + + ``` + +### WEAR_DETECTION(deprecated) + +once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void + +Subscribes to only one data change of the wear detection sensor. + +This API is deprecated since API version 9. You are advised to use [sensor.once.WEAR_DETECTION](#wear_detection9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + + ```js + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { + console.info("Wear status: "+ data.value); + } + ); + + ``` + +## sensor.off(deprecated) + +### ACCELEROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER](#accelerometer9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('x-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); + +``` + +### ACCELEROMETER_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ACCELEROMETER_UNCALIBRATED](#accelerometer_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**. | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); + +``` + +### AMBIENT_LIGHT(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_LIGHT](#ambient_light9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**. | +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | + +**Example** + +```js +function callback(data) { + console.info(' Illumination: ' + data.intensity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); + +``` + +### AMBIENT_TEMPERATURE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.AMBIENT_TEMPERATURE](#ambient_temperature9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**. | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Temperature: ' + data.temperature); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); + +``` + +### BAROMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.BAROMETER](#barometer9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Atmospheric pressure: ' + data.pressure); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); +``` + +### GRAVITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GRAVITY](#gravity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); +``` + +### GYROSCOPE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE](#gyroscope9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); + +``` + +### GYROSCOPE_UNCALIBRATED(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.GYROSCOPE_UNCALIBRATED](#gyroscope_uncalibrated9-2) instead. + +**Required permissions**: ohos.permission.GYROSCOPE + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**. | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); + +``` + +### HALL(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HALL](#hall9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Status: ' + data.status); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); + +``` + +### HEART_RATE(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_BEAT_RATE](#heart_beat_rate9) instead. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +### HEART_BEAT_RATE9+ + +off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.HEALTH_DATA + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | + +**Example** + +```js +function callback(data) { + console.info("Heart rate: " + data.heartRate); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); + +``` + +### HUMIDITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.HUMIDITY](#humidity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Humidity: ' + data.humidity); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); + +``` + +### LINEAR_ACCELERATION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +### LINEAR_ACCELEROMETER9+ + +off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback?:Callback<LinearAccelerometerResponse>): void + +Unsubscribes from sensor data changes. + +**Required permissions**: ohos.permission.ACCELEROMETER + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); + +``` + +### MAGNETIC_FIELD(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD](#magnetic_field9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); + +``` + +### MAGNETIC_FIELD_UNCALIBRATED(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.MAGNETIC_FIELD_UNCALIBRATED](#magnetic_field_uncalibrated9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**. | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); + +``` + +### ORIENTATION(deprecated) + + off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ORIENTATION](#orientation9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | + +**Example** + +```js +function callback(data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); + +``` + +### PEDOMETER(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER](#pedometer9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Steps: ' + data.steps); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); + +``` + +### PEDOMETER_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PEDOMETER_DETECTION](#pedometer_detection9-2) instead. + +**Required permissions**: ohos.permission.ACTIVITY_MOTION + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**. | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); +``` + +### PROXIMITY(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.PROXIMITY](#proximity9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Distance: ' + data.distance); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); +``` + +### ROTATION_VECTOR(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.ROTATION_VECTOR](#rotation_vector9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**. | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | + +**Example** + +```js +function callback(data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); + +``` + +### SIGNIFICANT_MOTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.SIGNIFICANT_MOTION](#significant_motion9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**. | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | + +**Example** + +```js +function callback(data) { + console.info('Scalar data: ' + data.scalar); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); + +``` + +### WEAR_DETECTION(deprecated) + +off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void + +Unsubscribes from sensor data changes. + +This API is deprecated since API version 9. You are advised to use [sensor.off.WEAR_DETECTION](#wear_detection9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**. | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | + +**Example** + +```js +function accCallback(data) { + console.info('Wear status: ' + data.value); +} +sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); + +``` + +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated. | + +**Example** + +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { + if (err) { + console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Operation successed. Data obtained: " + data); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }) + +``` + +## sensor.transformCoordinateSystem(deprecated) + +transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> + +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.transformRotationMatrix](#sensortransformrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ----------------------------------------- | --------- | ----------------------------------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated. | + +**Example** + +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + promise.then((data) => { + console.info("Operation successed."); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) + +``` + +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void + +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | + +**Example** + +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { + if (err) { + console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); +}); + +``` + +## sensor.getGeomagneticField(deprecated) + +getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> + +Obtains the geomagnetic field of a geographic location. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getGeomagneticInfo](#sensorgetgeomagneticinfo9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ----------------------------------- | --------- | ------------------------------------------------------------ | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------------- | --------------------------------------------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | + +**Example** + + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); + promise.then((data) => { + console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + }).catch((reason) => { + console.info('Operation failed.'); + }) + + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | + +**Example** + + ```js + sensor.getAltitude(0, 200, function(err, data) { + if (err) { + console.error( + "Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Successed to get getAltitude interface get data: " + data); + }); + + ``` + +## sensor.getAltitude(deprecated) + +getAltitude(seaPressure: number, currentPressure: number): Promise<number> + +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getDeviceAltitude](#sensorgetdevicealtitude9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------- | ------ | --------- | ------------------------------------------------------------ | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the altitude, in meters. | + +**Example** + + ```js + const promise = sensor.getAltitude(0, 200); + promise.then((data) => { + console.info(' sensor_getAltitude_Promise success', data); + }).catch((err) => { + console.error("Operation failed"); + }) + + ``` + + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void + +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | --------------------------- | --------- | ----------------------------------------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians. | + +**Example** + + ```js + sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + + err.message); + return; + } + console.info("Successed to get getGeomagneticDip interface get data: " + data); + }) + ``` + +## sensor.getGeomagneticDip(deprecated) + +getGeomagneticDip(inclinationMatrix: Array<number>): Promise<number> + +Obtains the magnetic dip based on the inclination matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getInclination](#sensorgetinclination9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------------- | ------------------- | --------- | ------------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians. | + +**Example** + + ```js + const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('getGeomagneticDip_promise successed', data); + }).catch((err) => { + console.error("Operation failed"); + }) + ``` + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { + if (err) { + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor. getAngleModify(deprecated) + +getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the angle change between two rotation matrices. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getAngleVariation](#sensorgetanglevariation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------------------- | ------------------- | --------- | -------------------------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); + promise.then((data) => { + console.info('getAngleModifiy_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | -------------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------- | +| Promise<Array<number>> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createRotationMatrix_promise success'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((reason) => { + console.info("promise::catch", reason); + }) + + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void + +Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | --------------------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | + +**Example** + + ```js + sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }) + + ``` + + +## sensor.createQuaternion(deprecated) + +createQuaternion(rotationVector: Array<number>): Promise<Array<number>> + +Converts a rotation vector into a quaternion. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getQuaternion](#sensorgetquaternion9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | --------------------------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert. | + +**Return value** + +| Type | Description | +| ---------------------------------- | -------------------------------------- | +| Promise<Array<number>> | Promise used to return the quaternion. | + +**Example** + + ```js + const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); + promise.then((data) => { + console.info('createQuaternion_promise successed'); + for (var i=0; i < data.length; i++) { + console.info("data[" + i + "]: " + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void + +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { + if (err) { + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + err.message); + return; + } + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_callback" + data[i]); + } + }) + + ``` + + +## sensor.getDirection(deprecated) + +getDirection(rotationMatrix: Array<number>): Promise<Array<number>> + +Obtains the device direction based on the rotation matrix. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getOrientation](#sensorgetorientation9-1) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | --------- | ---------------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------------------------------------------------ | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes. | + +**Example** + + ```js + const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); + promise.then((data) => { + console.info('sensor_getAltitude_Promise success', data); + for (var i = 1; i < data.length; i++) { + console.info("sensor_getDirection_promise" + data[i]); + } + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-2) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------------------------------------ | --------- | -------------------------------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix. | + +**Example** + + ```js + sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { + if (err) { + console.error('error code is: ' + err.code + ', message: ' + err.message); + return; + } + console.info(JSON.stringify(data)); + }) + ``` + + +## sensor.createRotationMatrix(deprecated) + +createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>,): Promise<RotationMatrixResponse> + +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [sensor.getRotationMatrix](#sensorgetrotationmatrix9-3) instead. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | --------- | ------------------- | +| gravity | Array<number> | Yes | Gravity vector. | +| geomagnetic | Array<number> | Yes | Geomagnetic vector. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix. | + +**Example** + + ```js + const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); + promise.then((data) => { + console.info(JSON.stringify(data)); + }).catch((err) => { + console.info('promise failed'); + }) + ``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 658082d2690c0ab00d76959a1a7ce1c97574ce5d..10f08e3b588e7c03d44ef3eac6ade39a42a5febe 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -29,15 +29,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total size of the volume.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the total size of the volume.| **Example** @@ -66,10 +66,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| **Example** @@ -97,15 +97,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the volume.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the volume.| **Example** @@ -135,10 +135,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | ---------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ---------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| **Example** @@ -166,15 +166,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | ------ | ---- | -------- | - | packageName | string | Yes | Bundle name of the application.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------- | +| packageName | string | Yes | Bundle name of the application.| **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| **Example** @@ -203,10 +203,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| packageName | string | Yes | Bundle name of the application.| +| callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| **Example** @@ -228,9 +228,9 @@ Asynchronously obtains space information of the current third-party application. **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | **Example** @@ -249,9 +249,9 @@ Asynchronously obtains space information of the current third-party application. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | **Example** @@ -294,9 +294,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the total space of the built-in memory card. | +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the total space of the built-in memory card. | **Example** @@ -321,9 +321,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------ | ---- | ------------------------ | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| **Example** @@ -351,9 +351,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the built-in memory card.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the built-in memory card.| **Example** @@ -379,9 +379,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| **Example** @@ -408,9 +408,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the system space obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the system space obtained.| **Example** @@ -438,9 +438,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| **Example** @@ -467,15 +467,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| **Example** @@ -504,10 +504,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | - | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | +| callback | callback:AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| **Example** diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animate.md b/en/application-dev/reference/arkui-js/js-components-svg-animate.md index 751dbe4adb724775bc0cd287b47f29c25cbd2339..f214967694d8534769932d1b1f0e9d95dc54e61f 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animate.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animate.md @@ -1,19 +1,20 @@ -# animate +# animate The **** component is used to apply animation to an **** component. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>![](../../public_sys-resources/icon-note.gif) **NOTE** +> >This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +## Required Permissions None -## Child Components +## Child Components Not supported -## Attributes +## Attributes

Name

@@ -193,7 +194,7 @@ Not supported
-## Example +## Example ``` diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png new file mode 100644 index 0000000000000000000000000000000000000000..5855095851b92058f270d69a46546db43ec974b8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 96bedd577f9bdf9431957ddd52735bda35a60808..df5bc74f017aedfc698e85fd88f9e39f00bcb29d 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -89,4 +89,4 @@ struct PathExample { } ``` -![zh-cn_image_0000001219744193](figures/zh-cn_image_0000001219744193.png) +![en-us_image_0000001219744193](figures/en-us_image_0000001219744193.png) diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 816afa1fd4810afcdd57565bbf806a77de1f8331..5b082bc803d6d82e93c273fc1ea9ba4ddfd25ce1 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -2031,6 +2031,8 @@ Resets the existing transformation matrix and creates a new transformation matri ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) +### translate + ### translate translate(x: number, y: number): void diff --git a/en/application-dev/ui/ts-pixel-units.md b/en/application-dev/ui/ts-pixel-units.md index a626608016ebfaa97f0a9a92dcfbdc2ce3bf7004..ca95e08be83c3d40d12fba614e11d58470be2f16 100644 --- a/en/application-dev/ui/ts-pixel-units.md +++ b/en/application-dev/ui/ts-pixel-units.md @@ -4,31 +4,31 @@ The framework provides four pixel units, with vp as the reference data unit. -| Name | Description | +| Name | Description | | -------- | -------- | -| px | Physical pixel unit of the screen. | -| vp | Pixels specific to the screen density, which are converted into physical pixels of the screen based on the screen pixel density. | -| fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by [designWidth](../ui/ts-framework-js-tag.md)). For example, if designWidth is set to 720, then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | +| px | Physical pixel unit of the screen. | +| vp | Pixels specific to the screen density, which are converted into physical pixels of the screen based on the screen pixel density. | +| fp | Font pixel, which is similar to vp and varies according to the system font size. | +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by [designWidth](../quick-start/package-structure.md)). For example, if designWidth is set to 720, then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | ## Pixel Unit Conversion Conversion from other pixel units to px is supported. - | API | Description | +| API | Description | | -------- | -------- | -| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | -| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | -| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | -| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | -| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px. | -| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx. | +| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | +| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | +| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | +| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | +| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px. | +| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx. | ## Example - + ```ts // xxx.ets @Entry diff --git a/en/contribute/OpenHarmony-c-coding-style-guide.md b/en/contribute/OpenHarmony-c-coding-style-guide.md index c63b38e5e982dd0c148bb771a617e1fb7eeb6ae6..bd2fdf2bdac82f3ecabfaef2759fd587542132eb 100755 --- a/en/contribute/OpenHarmony-c-coding-style-guide.md +++ b/en/contribute/OpenHarmony-c-coding-style-guide.md @@ -1,6 +1,6 @@ # C Coding Style Guide -## Purpose +## Purpose Rules are not perfect. They might disable useful features in specific situations and therefore affect code implementation. However, the purpose of developing rules is to get more benefits for most programmers. If a rule cannot be followed in your team operation, we can improve the rule together. Before referring to this coding style guide, you are expected to have the following basic capabilities of the C programming language: @@ -8,11 +8,11 @@ Rules are not perfect. They might disable useful features in specific situations 2. Be familiar with the basic features of C. 3. Understand the standard library of C. -## General Principles +## General Principles Code must meet the requirements for **readability**, **maintainability**, **security**, **reliability**, **testability**, **efficiency**, and **portability** while ensuring functionality correctness. -## Conventions +## Conventions **Rule**: Conventions that must be followed during programming. @@ -20,51 +20,64 @@ Code must meet the requirements for **readability**, **maintainability**, **secu It is necessary to understand the reason for these conventions and try to comply with them, no matter if they are rules or recommendations. -## Exceptions +## Exceptions + +The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence. -The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence. Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare. -The style consistency principle is preferred in the following case: +The style consistency principle is preferred in the following case: + **When you modify open-source or third-party code, comply with their respective code specifications.** -# 1 Naming +# 1 Naming Names include file, function, variable, type, and macro names. -Naming is considered the most difficult and important thing in software development. +Naming is considered the most difficult and important thing in software development. + The name of an identifier must be clear, well defined, easy to understand, and accounting for reading habits. The unified naming style is the most direct expression of the consistency principle. -## General Conventions +## General Conventions + +**CamelCase** -**CamelCase** CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. + There are two conventions: **UpperCamelCase and lowerCamelCase**. -**Unix\_like** +**Unix\_like** + Unix\_like is also known as the snake style. In the Unix\_like style, words contain only lowercase letters and are separated by underscores (\_). + Example: 'test_result' -### Rule 1.1 Name identifiers in the CamelCase style. +### Rule 1.1 Name identifiers in the CamelCase style. -| Type| Naming Style -|----------|---------- -| Function, struct, enum, union| UpperCamelCase -| Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase -| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_) +| Type| Naming Style| +|----------|----------| +| Function, struct, enum, union| UpperCamelCase| +| Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase| +| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_)| + +Note: -Note: **Constant** in the above table refers to the variable that is of the basic data type, enum type, and string type and modified by **const** under the global scope, excluding arrays, structs, and unions. + **Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style. + Unix\_like can be used for Linux or Unix friendly code. + For code that is using the Unix\_like style, you can continue using this style. + The same naming style must be used for the same function, struct, or union. -### Rec 1.1 Use more accurate names for identifiers with a large scope. +### Rec 1.1 Use more accurate names for identifiers with a large scope. + +Different from C++, C does not have namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other. -Different from C++, C does not have namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other. Names of global functions, global variables, macros, types, and enums must be accurately described and unique in the global scope. Example: @@ -75,7 +88,9 @@ int GetActiveConnectCount(void); // Good ``` For purposes of accurate naming, a module prefix can be added if necessary. -The module prefix and the naming body can be connected by following the CamelCase style. + +The module prefix and the naming body can be connected by following the CamelCase style. + Example: ```c @@ -86,26 +101,30 @@ enum XxxMyEnum { // OK }; ``` -## File Naming +## File Naming -### Rec 1.2 Use lowercase file names. +### Rec 1.2 Use lowercase file names. Only lowercase letters, numbers, and underscores (\_) are allowed in file names. -File names should be as short, accurate, and unambiguous as possible. + +File names should be as short, accurate, and unambiguous as possible. + The reason for using lowercase file names is that different systems process file names in different ways. (For example, file names in MS-DOS and Windows are not case sensitive, but those in Unix/Linux and macOS are case sensitive by default). -Good example: +Good example: + `dhcp_user_log.c` Bad examples: + `dhcp_user-log.c`: It is not recommended that you separate words with the hyphen (-). `dhcpuserlog.c`: The words are not separated, causing poor readability. -## Function Naming +## Function Naming Functions are named in the UpperCamelCase style. -### Rec 1.3 Name functions to comply with reading habits. +### Rec 1.3 Name functions to comply with reading habits. The "verb + object" structure can be used for action related function names. Example: @@ -130,13 +149,14 @@ TotalCount() // OK GetTotalCount() // OK ``` -## Variable Naming +## Variable Naming Variables are named in the lowerCamelCase style. This includes global variables, local variables, parameters in the function declaration or definition as well as parameters in function-like macro. -### Rule 1.2 Add the 'g_' prefix to global variables, but not to static variables in a function. +### Rule 1.2 Add the 'g_' prefix to global variables, but not to static variables in a function. Global variables should be used as little as possible, and special attention should be paid to their use. This prefix highlights global variables so that developers can be more careful when handling them. + Global static variables and global variables are named in the same way. Static variables in functions and common local variables are named in the same way. ```c @@ -151,7 +171,7 @@ void Func(void) Notes: Constants are also global variables in essence. However, if constants are named using uppercase letters separated by underscores (\_), the current rule does not apply. -### Rec 1.4 Keep local variables short and to the point. +### Rec 1.4 Keep local variables short and to the point. The name of a local variable should be short on the premise that meanings can be expressed through context. @@ -184,6 +204,7 @@ int Func(...) ``` Similarly, "tmp" can be used to address any type of temporary variable. + A short variable name should be used with caution, but sometimes a single-character variable is allowed, for example, a counter variable in a loop statement. ```c @@ -203,7 +224,7 @@ int Mul(int a, int b) } ``` -## Type Naming +## Type Naming Types are named in the UpperCamelCase style. @@ -248,14 +269,18 @@ typedef struct tagNode { // Good: Add the 'tag' prefix or use 'Node_'. } Node; // UpperCamelCase. ``` -## Macro, Constant, and Enum Naming +## Macro, Constant, and Enum Naming Use uppercase letters separated by underscores (\_) for macro names and enumerated values. + You are advised to use uppercase letters separated with underscores (\_) for constant names. Global const variables can be named with the same style of global variables. + The constants here are defined as global const variables of the basic data type, enum type, or string type. Use uppercase letters separated by underscores (\_) for function-like macros. + Exceptions: + 1. Functions that use macros to implement generic functions, for example, macros that implement functions such as list and map, can be named in the same way as functions, using the UpperCamelCase style. 2. A function-like macro that is used to replace a function in the earlier version can be named in the same way as functions, using the UpperCamelCase style. 3. Macros for printing logs can be named in the same way as functions, using the UpperCamelCase style. @@ -317,7 +342,7 @@ enum BaseColor { }; ``` -### Rec 1.5 Avoid temporary variables in function-like macros from polluting external scopes. +### Rec 1.5 Avoid temporary variables in function-like macros from polluting external scopes. **If possible, use a function instead of a function-like macro. Define a function-like macro only when necessary.** @@ -330,15 +355,18 @@ When defining local variables for a function-like macro, use double underscores } while (0) ``` -# 2 Formatting +# 2 Formatting -## Line Length +## Line Length -### Rule 2.1 Include 120 characters or less in each line. +### Rule 2.1 Include 120 characters or less in each line. A longer line makes it more difficult for reading. + To meet the line length requirement, you can shorten the names of functions and variables and reduce the number of nesting layers. This improves code readability. + Unless a long line is necessary to maintain readability and present complete information, steer your document clear of long lines. + Even on a high-resolution monitor, a long line increases the difficulty of reading. Strive for clearness and conciseness. Exceptions: @@ -354,19 +382,22 @@ Example: #endif ``` -## Indentation +## Indentation -### Rule 2.2 Use spaces to indent and indent four spaces at a time. +### Rule 2.2 Use spaces to indent and indent four spaces at a time. + +Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. -Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. Currently, almost all integrated development environments (IDEs) and code editors support automatic conversion of a Tab input to fours spaces. Configure your code editor to support indentation with spaces. -## Braces +## Braces + +### Rule 2.3 Use the K\&R indentation style. + +**K\&R style** -### Rule 2.3 Use the K\&R indentation style. +While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. -**K\&R style** -While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. The right brace takes a single line, unless it is followed by the rest of the same statement, such as `while` in the `do` statement, `else` or `else if` in the `if` statement, a comma, or a semicolon. Example: @@ -386,9 +417,9 @@ int Foo(int a) } ``` -## Function Declaration and Definition +## Function Declaration and Definition -### Rule 2.4 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. +### Rule 2.4 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. When a function is declared and defined, the return value type of the function should be in the same line as the function name. @@ -423,11 +454,12 @@ ReturnType ReallyReallyReallyReallyLongFunctionName( // The line leng } ``` -## Function Calls +## Function Calls -### Rule 2.5 Align the parameter list appropriately if it needs to be wrapped. +### Rule 2.5 Align the parameter list appropriately if it needs to be wrapped. In a function call, if the function parameter list is wrapped, it should be aligned appropriately. + The left parenthesis is always followed by a function name, and the right parenthesis always follows the last parameter. Example: @@ -454,11 +486,12 @@ int result = DealWithStructureLikeParams(left.x, left.y, // Indicates a grou right.x, right.y); // Indicates another group of related parameters. ``` -## Conditional Statements +## Conditional Statements -### Rule 2.6 Use braces for conditional statements. +### Rule 2.6 Use braces for conditional statements. Use braces to enclose conditional statements, even if there is only one statement. + Reason: - Logic is intuitive and easy to read. @@ -471,7 +504,7 @@ if (objectIsNotExist) { // Good: Braces are added to a single-line condi } ``` -### Rule 2.7 Do not place `if`, `else`, and `else if` in the same line. +### Rule 2.7 Do not place `if`, `else`, and `else if` in the same line. In a conditional statement, branches, if any, should be written in different lines. @@ -491,9 +524,9 @@ Bad example: if (someConditions) { ... } else { ... } // Bad: They are in the same line. ``` -## Loops +## Loops -### Rule 2.8 Use braces for loop statements. +### Rule 2.8 Use braces for loop statements. Use braces to enclose the `for` and `while` statements, even if there is only one loop. @@ -524,9 +557,9 @@ for (int i = 0; i < someRange; i++) while (condition); // Bad: The semicolon may be treated as part of the `while` statement. ``` -## `switch` Statements +## `switch` Statements -### Rule 2.9 Indent the `case` or `default` statement in a `switch` statement block. +### Rule 2.9 Indent the `case` or `default` statement in a `switch` statement block. Use the following indentation style for the `switch` statement: @@ -554,9 +587,9 @@ default: // Bad: 'default' not indented } ``` -## Expressions +## Expressions -### Rec 2.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of the line. +### Rec 2.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of the line. A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped after a lower-priority operator or a hyphen, and the operator or hyphen is placed at the end of the line, indicating that the operation is to be continued. @@ -584,9 +617,9 @@ int sum = longVariableName1 + longVariableName2 + longVariableName3 + longVariableName4 + longVariableName5 + longVariableName6; // OK: aligned ``` -## Variable Assignment +## Variable Assignment -### Rule 2.10 Do not write multiple variable definitions or assignment statements in one line. +### Rule 2.10 Do not write multiple variable definitions or assignment statements in one line. It is recommended that each line contain only one variable initialization statement, which is easier to read and understand. @@ -619,13 +652,14 @@ for (i = 0; i < row; i++) { } ``` -## Initialization +## Initialization Initialization is applicable to structs, unions, and arrays. -### Rule 2.11 Use indentation or make a reasonable alignment for a new line. +### Rule 2.11 Use indentation or make a reasonable alignment for a new line. For the struct or array initialization, use 4 spaces for indentation if a line break is made. + From better readability, make a reasonable alignment. ```c @@ -669,7 +703,7 @@ Note: - If the left brace is placed at the end of the line, the corresponding right brace should be placed into a new line. - If the left brace is followed by the content, the corresponding right brace should also follow the content. -### Rule 2.12 Initialize each member in a separate line during struct and union member initialization. +### Rule 2.12 Initialize each member in a separate line during struct and union member initialization. The C99 standard supports the initialization of the struct and union members in their definition. This is called the designated initializer. In such a way, each member should be initialized in a separate line. @@ -687,9 +721,9 @@ struct Date date = { // Good: When the designated initializer is used, each m }; ``` -## Pointers +## Pointers -### Rec 2.2 Ensure that the asterisk (\*) in the pointer type is followed by the variable name or follows the type. There must be a space before or after the asterisk. +### Rec 2.2 Ensure that the asterisk (\*) in the pointer type is followed by the variable name or follows the type. There must be a space before or after the asterisk. When you declare or define a pointer variable or return a pointer type function, the asterisk can be placed on the left (following the type) or right (followed by the variable name). There must be only one space before or after the asterisk. @@ -719,16 +753,17 @@ int Foo(const char * restrict p); // OK Do not use the asterisk to follow the `const` or `restrict` keywords. -## Compilation Preprocessing +## Compilation Preprocessing -### Rule 2.13 Place the number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. +### Rule 2.13 Place the number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body. + Try your best not to use compilation preprocessing macros. If they are needed in deed, they should be managed by dedicated personnel in a unified manner. -## Whitespace +## Whitespace -### Rule 2.14 Use horizontal whitespaces to highlight keywords and important information, and avoid unnecessary whitespaces. +### Rule 2.14 Use horizontal whitespaces to highlight keywords and important information, and avoid unnecessary whitespaces. Horizontal spaces should be used to highlight keywords and important information. Do not add spaces at the end of each line of code. The general rules are as follows: @@ -821,7 +856,7 @@ switch (var) { // Good: A space is added after the `switch` keyword. Note: The current IDE and code editor can be set to delete spaces at the end of a line. Configure your editor correctly. -### Rec 2.3 Arrange blank lines reasonably to keep the code compact. +### Rec 2.3 Arrange blank lines reasonably to keep the code compact. Reduce unnecessary blank lines so that more code can be displayed for easy reading. The following rules are recommended: @@ -862,7 +897,7 @@ int Foo(void) } ``` -# 3 Comments +# 3 Comments Generally, clear architecture and good symbol naming are recommended to improve code readability, and comments are provided only when necessary. @@ -873,6 +908,7 @@ The comments must be concise, clear, and unambiguous, ensuring that the informat **Comments are as important as code.** When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the code functionality and intention, rather than repeating code. + When modifying the code, ensure that the comments are consistent. It is impolite to only modify code and not update the comments. This destroys the consistency between code and comments, and may cause confusion or even misleading. Comment code in fluent **English**. @@ -883,18 +919,19 @@ Comments must be added in the following scenarios (including but not limited to 3. Core algorithms 4. A function that contains more than 50 lines -## Comment Style +## Comment Style In C code, both `/*` `*/` and `//` can be used. Comments can be classified into different types depending on the purpose and position, such as file header comments, function header comments, and general comments. + Comments of the same type must keep a consistent style. Note: The sample code used in this article sees extensive use of the '//' post-comment. This is only for better understanding, and does not mean that this comment style is better. -## File Header Comments +## File Header Comments -### Rule 3.1 Include the copyright license in the file header comments. +### Rule 3.1 Include the copyright license in the file header comments. /\* @@ -911,9 +948,9 @@ Note: The sample code used in this article sees extensive use of the '//' post-c * See the License for the specific language governing permissions and * limitations under the License. \*/ -## Function Header Comments +## Function Header Comments -### Rule 3.2 Do not use empty function header comments with no content. +### Rule 3.2 Do not use empty function header comments with no content. Not all functions need function header comments. @@ -947,10 +984,12 @@ int Func1(void); int Func2(void); ``` -Use function names to describe functions, and only add function header comments if necessary. +Use function names to describe functions, and only add function header comments if necessary. + Do not write useless or redundant function headers. Do not write empty function headers with no content. The following content is **optional** in the function header comment: function description, return value, performance constraint, usage, memory convention, algorithm implementation, and reentering requirement. + In the function interface declaration in the external header file of the module, the function header comment should clearly describe important and useful information. Example: @@ -981,11 +1020,11 @@ Problems in the preceding example are as follows: - The function name has redundant information. - It does not clearly state the party that should release the buffer. -## Code Comments +## Code Comments -### Rule 3.3 Place code comments above or to the right of the code. +### Rule 3.3 Place code comments above or to the right of the code. -### Rule 3.4 Add a space between the comment character and the comment content, and one space between the comment and code if the comment is placed to the right of the code. +### Rule 3.4 Add a space between the comment character and the comment content, and one space between the comment and code if the comment is placed to the right of the code. Comments placed above code should be indented to the same level as the code. @@ -1041,14 +1080,15 @@ Example: If the comment on the right exceeds the permitted line length, the comment can be placed above the code. -### Rule 3.5 Delete unused code segments. Do not comment them out. +### Rule 3.5 Delete unused code segments. Do not comment them out. + +Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects. -Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects. The correct method is to delete unnecessary code. If necessary, consider porting or rewriting the code. Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /\* \*/, //, #if 0, #ifdef NEVER\_DEFINED, and so on. -### Rec 3.1 Provide comments if `break` or `return` is not added to the end of the `case` statement block (fall-through). +### Rec 3.1 Provide comments if `break` or `return` is not added to the end of the `case` statement block (fall-through). Sometimes, the same thing is needed for multiple `case` tags. When a `case` statement ends without `break` or `return`, the statement in the next `case` tag will be executed. This is called "fall-through". @@ -1085,14 +1125,15 @@ switch (var) { } ``` -# 4 Header Files +# 4 Header Files **For the C programming language, the design of the header file reflects most of the system design.** + The correct use of the header file makes code more readable, reduces file size, and speeds up compilation and build performance. The following programming specifications aim to help you properly plan header files. -## Header File Responsibility +## Header File Responsibility A header file is an external interface of a module or file. @@ -1107,7 +1148,8 @@ If a .c file does not need to open any interface externally, it should not exist Exceptions: the entry point of the program (for example, the file where the main function is located), unit test code, and dynamic library code. -Example: +Example: + Content of **foo.h**: ```c @@ -1147,28 +1189,33 @@ Some simple header files, such as the command ID definition header file, do not If a set of interface protocols has multiple instances and the interface is fixed, one .h file can have multiple .c files. -### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc. +### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc. + +Some products use .inc as the header file name extension, which does not comply with the C programming language. A header file using .inc as the file name extension usually indicates a private header file. -Some products use .inc as the header file name extension, which does not comply with the C programming language. A header file using .inc as the file name extension usually indicates a private header file. However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. It is not recommended that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). +However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. It is not recommended that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). -## Header File Dependency +## Header File Dependency + +The header file contains a dependency, and the dependency should be stable. -The header file contains a dependency, and the dependency should be stable. Generally, an unstable module depends on a stable module. When the unstable module changes, the build of the stable module is not affected. Dependency direction is as follows: Products depend on the platform, and the platform depends on the standard library. -In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module. +In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module. + It is assumed that the interface is the most stable. -### Rule 4.1 Forbid cyclic dependency of header files. +### Rule 4.1 Forbid cyclic dependency of header files. + +Cyclic dependency (also known as a circular dependency) of header files means that a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any header file is modified, all code containing a.h, b.h, and c.h needs to be recompiled. -Cyclic dependency (also known as a circular dependency) of header files means that a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any header file is modified, all code containing a.h, b.h, and c.h needs to be recompiled. For a unidirectional dependency: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean a need to recompile the source code for b.h or c.h. The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization. -### Rule 4.2 Include the internal #include protection character (#define protection) in the header file. +### Rule 4.2 Include the internal #include protection character (#define protection) in the header file. To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once. @@ -1187,13 +1234,16 @@ Assume that the **timer.h** file of the timer component of the util subsystem is #endif // UTIL_TIMER_TIMER_H ``` -### Rule 4.3 Do not reference external function interfaces and variables by using declaration. +### Rule 4.3 Do not reference external function interfaces and variables by using declaration. + +You can use the interfaces provided by other modules or files only by using header files. + +Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed. -You can use the interfaces provided by other modules or files only by using header files. -Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed. In addition, this kind of implicit dependency may cause architecture corruption. Cases that do not comply with specifications: + Content of **a.c**: ```c @@ -1233,11 +1283,14 @@ int Foo(void) ``` In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. + Example: -When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. + +When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. + When a function needs to be stubbed or patched, the function can be declared using extern. -### Rule 4.4 Do not include header files in extern "C". +### Rule 4.4 Do not include header files in extern "C". If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the number of nesting layers of extern "C". Too many nesting layers may cause compilation errors. @@ -1281,38 +1334,46 @@ extern "C" { } ``` -In the **a.h** file, the **Foo** function is intended to be a C++ free function following the C++ specifications. However, in the **b.h** file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of the **Foo** function is changed incorrectly. +In the **a.h** file, the **Foo** function is intended to be a C++ free function following the C++ specifications. + +However, in the **b.h** file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of the **Foo** function is changed incorrectly. Exceptions: In the C++ compilation environment, if you want to reference a header file written in pure C, a non-intrusive approach is to exclude the C header file from `extern "C"`. -# 5 Functions +# 5 Functions Functions help avoid repeated code and increase reusability. Functions are layered to reduce complexity and hide implementation details, making programs more modular and facilitating code reading and maintenance. Functions should be concise and short. + One function completes only one thing. -## Function Design +## Function Design The essence of function design is to write clean functions and organize code effectively. The code should be simple and not conceal the designer's intention, using clean abstractions and straightforward control statements to organize the function naturally. -### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (excluding blank lines and comments). +### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (excluding blank lines and comments). A function should be able to be displayed on one screen (fewer than 50 lines). It does only one thing and does it well. A long function usually means that it aims to implement complex functionalities or contains excess details. Exceptions: -Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise. + +Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise. + These exceptions should be minimal, such as specific algorithm processing. -Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover. +Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover. + It is recommended that you split the code into several functions that are simpler and easier to manage so that others can easily read and modify the code. -### Rule 5.2 Avoid nesting a code block more than four times within a function. +### Rule 5.2 Avoid nesting a code block more than four times within a function. The nested code block depth of a function refers to the layered depth of a code control block (created by statements such as `if`, `for`, `while`, and `switch`). + Each layer of nesting increases the difficulty in reading the code. + Further functional decomposition should be done for better understanding. Using `guard clauses` can effectively reduce the nesting layers of the `if` statements. Example: @@ -1350,10 +1411,12 @@ int Foo(...) ``` Exceptions: + Considering the code's aggregation and functionality, some functions may contain 4 or more nesting layers, but only if the code is readable and concise. + These exceptions should be rare. -### Rec 5.1 Process all returned error codes. +### Rec 5.1 Process all returned error codes. A function (in a standard library, a third-party library, or a user-defined function) must be able to indicate errors. This can be done by using error tags, special return data, or other means. No matter when a function provides such a mechanism, the caller should immediately check the error indication after the function returns. @@ -1379,11 +1442,12 @@ DealWithFileHead(fileHead, sizeof(fileHead)); // Process the file header. ``` If the return value of a function is ignored and `void` is returned frequently, check whether the return value of the function is designed properly. + Only if the caller of a function really doesn't need a return value, should you design the function to return `void`. -## Function Parameters +## Function Parameters -### Rec 5.2 Use the return value instead of the output parameter when designing a function. +### Rec 5.2 Use the return value instead of the output parameter when designing a function. Using return values rather than output parameters improves readability and usually provides the same or better performance. @@ -1393,17 +1457,18 @@ Exceptions: 1. When multiple values are returned, you can design an output parameter for the function. 2. If memory allocation is involved, you can design an output parameter. The caller passes the allocated memory as an output parameter, and memory allocation is not performed in the function. -### Rec 5.3 Define function parameters in the sequence of input, output, and input/output parameters. +### Rec 5.3 Define function parameters in the sequence of input, output, and input/output parameters. You are advised to define function parameters in the sequence of input, output, and input/output parameters. -### Rule 5.3 Provide a release function if allocation of resources, such as memory, locks, and queues, is involved. +### Rule 5.3 Provide a release function if allocation of resources, such as memory, locks, and queues, is involved. Resources should be released from where they are applied for. If a function applies for resources, the module must provide resource functions. -### Rec 5.4 Use strongly typed parameters. Do not use void\*. +### Rec 5.4 Use strongly typed parameters. Do not use void\*. + +While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style. -While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style. The advantage of this strongly typed style is to prevent evasive errors by catching errors at the compilation stage. Strong types help the compiler find more errors.Pay attention to the usage of the `FooListAddNode` function in the following code: @@ -1448,12 +1513,14 @@ void FooListAddNode(FooNode *foo) Exceptions: For some generic interfaces, you can use the input parameter `void *` to pass different types of pointers. -### Rec 5.5 It is the caller's responsibility to check the validity of internal function parameters of a module. +### Rec 5.5 It is the caller's responsibility to check the validity of internal function parameters of a module. Validity check must be performed on parameters passed from external modules to protect programs from being damaged by invalid input data. + When calling internal functions, by default, the caller is responsible for ensuring the validity of any returned data. If the callee takes responsibility for checking data validity, checks may be performed multiple times and redundant code is generated. This is not concise. When the caller ensures the validity of any received data, this contractual programming makes logic simpler and code more readable. + Example: ```c @@ -1480,7 +1547,7 @@ void DealWithData(int data) } ``` -### Rec 5.5 Declare the pointer argument of a function as 'const' if it is not used to modify the pointed object. +### Rec 5.5 Declare the pointer argument of a function as 'const' if it is not used to modify the pointed object. The const pointer argument, which restricts the function from modifying the object through the pointer, makes code stronger and safer. @@ -1492,7 +1559,7 @@ int strncmp(const char *s1, const char *s2, size_t n); // Good: The invariant pa Note: Whether to declare the pointer parameter as `const` depends on the function design, but not on whether there is a "modify object" action in the function entity. -### Rec 5.6 Include no more than 5 parameters in a function. +### Rec 5.6 Include no more than 5 parameters in a function. If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increases the workload for testing. @@ -1501,11 +1568,11 @@ The number of parameters in a function must not exceed 5. If the number of param - Check whether the function can be split. - Check whether any related parameters can be combined and defined as a struct. -## Inline Functions +## Inline Functions -An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#rec-61-use-functions-instead-of-function-like-macros). +An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#a6-1). -### Rec 5.7 Include no more than 10 lines in an inline function (excluding blank lines and comments). +### Rec 5.7 Include no more than 10 lines in an inline function (excluding blank lines and comments). Defining a function as an inline function generally aims to improve performance, though it may fail to do so.If the function body is short, function inlining can effectively reduce the size of the target code and improve the function execution efficiency. @@ -1516,7 +1583,7 @@ It is recommended that inline functions be controlled to within **10** lines. Do not abuse inline functions to improve performance. Avoid premature optimization. In general, a function can be defined as an inline function only when actual test data proves that the inlining achieves higher performance. Functions such as setter and getter functions, which are short and called frequently, can be defined as inline functions. -### Rule 5.3 Define inline functions that will be called by multiple source files in the header file. +### Rule 5.3 Define inline functions that will be called by multiple source files in the header file. Inline functions are unfolded in compilation. Therefore, the inline function definition must be visible in each source file that calls this function. @@ -1548,11 +1615,12 @@ int OtherFunc(void) ``` Due to this restriction, if multiple source files need to call the same inline function, the definition of the inline function must be placed in the header file. + The inline function implementation in **gnu89** differs from that in the **C99** standard. For compatibility, you can declare the function as **static inline**. -# 6 Macros +# 6 Macros -## Function-like Macros +## Function-like Macros A function-like macro is a macro (as shown in the following example) similar to a function. It contains several statements to implement a specific function. @@ -1573,8 +1641,8 @@ Before defining a function-like macro, consider whether it can be replaced with The disadvantages of the function-like macro are as follows: - Function-like macros haves no type check, which is not as strict as the function call check. For the example code, see [Below](#macro_lack_of_type_check__example). -- If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#rule-61-use-complete-parentheses-for-macro-parameters-when-defining-a-macro) and [Rule 6.3](#rule-63-do-not-pass-expressions-with-side-effects-to-a-function-like-macro). -- A macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#rule-62-place-implementation-statements-of-function-like-macros-that-contain-multiple-statements-in-a-do-while0) may be generated. +- If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#r6-1) and [Rule 6.3](#r6-3). +- A macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#r6-2) may be generated. - There are high skill requirements on the proper use of macros (for example, the usage of `#` and wide use of parentheses), which reduces readability. - Extensions of some macros can only be implemented by specific compilers in specific scenarios, such as `statement expression` of `gcc`, reducing the portability. - After the macro is expanded during precompilation, it is invisible during subsequent compilation, linking, and debugging. Besides, macros that contain multiple lines are expanded into a line. @@ -1630,7 +1698,8 @@ int ErrLog(const char *file, unsigned long line, const char *fmt, ...); ### Rule 6.1 Use complete parentheses for macro parameters when defining a macro. -The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code. +The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code. + The expression after combination may result in a different result than expected, especially when the macro parameter is in an expression. The following is an incorrect format: @@ -1639,15 +1708,18 @@ The following is an incorrect format: #define SUM(a, b) a + b // Bad ``` -When the macro is used, the execution result is inconsistent with the expected result. -`100 / SUM(2, 8)` is expanded to `(100 / 2) + 8`. The expected result is `100 / (2 + 8)`. +When the macro is used, the execution result is inconsistent with the expected result. + +`100 / SUM(2, 8)` is expanded to `(100 / 2) + 8`. The expected result is `100 / (2 + 8)`. + This problem can be solved by adding parentheses to the entire expression, as shown in the following: ```c #define SUM(a, b) (a + b) // Bad ``` -However, this method has the following problems: +However, this method has the following problems: + `SUM(1 << 2, 8)` is extended to `1 << (2 + 8)` (because the priority of `<<` is lower than that of `+`), which is inconsistent with the expected result `(1 << 2) + 8`. To solve this problem, add parentheses to each macro parameter, as shown in the following: @@ -1721,7 +1793,8 @@ To solve the preceding problem, use braces to enclose the statements defined by } ``` -The brackets are not associated with semicolons (;). The semicolon following the braces is another statement. +The brackets are not associated with semicolons (;). The semicolon following the braces is another statement. + In the following code example, the "suspended else' compilation error message is displayed. ```c @@ -1749,7 +1822,8 @@ Exceptions: ### Rule 6.3 Do not pass expressions with side effects to a function-like macro. -Since macros are replaced by text, if a function-like macro uses the same macro parameter multiple times and transfers expressions with side effects as macro parameters, unexpected results may occur. +Since macros are replaced by text, if a function-like macro uses the same macro parameter multiple times and transfers expressions with side effects as macro parameters, unexpected results may occur. + As shown in the following example, the macro `SQUARE` is normal, but the `a++` expression with side effects is passed to the macro. As a result, the value of `a` is different from the expected value after the `SQUARE` macro is executed. ```c @@ -1769,10 +1843,11 @@ b = SQUARE(a); a++; // Result: a = 6, which is added only once. ``` -In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded. +In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded. + If the function execution results are the same, it is a waste; if the results are different, the execution result may not meet the expected value. -### Rec 6.2 Exercise caution when you use the statements such as `return`, `goto`, `continue`, and `break` in a function-like macro definition. +### Rec 6.2 Exercise caution when you use the statements such as `return`, `goto`, `continue`, and `break` in a function-like macro definition. Although process changing statements, such as `return`, `goto`, `continue`, and `break`, in a macro can simplify the code, they hide the real process, which hinders understanding and easily causes resource leakage. @@ -1821,27 +1896,32 @@ CHECK_PTR(mem2, ERR_CODE_XXX); // Wrong: Memory leak. ``` If `mem2` fails to apply for memory, `CHECK_PTR` will return a message instead of releasing `mem1`. + Besides, the name of the `CHECK_PTR` macro is not good. The macro name only reflects the check action and does not specify the result. Readers can see that a failure is returned when the pointer is null only after viewing the macro implementation. It's not inherently obvious. In summary, it is not recommended to encapsulate process changing statements, such as `return`, `goto`, `continue`, and `break`, in macro definitions. + However, these macros can be used in special scenarios, such as return value judgment. Note: **Macro names must contain descriptive keywords if process changing statements, such as `return`, `goto`, `continue`, and `break`, are used.** -### Rec 6.3 Include no more than 10 lines in a function-like macro (excluding blank lines and comments). +### Rec 6.3 Include no more than 10 lines in a function-like macro (excluding blank lines and comments). A function-like macro is more difficult to debug and locate than a function, especially when the macro is too long. Macro expansion will also lead to more compiled code. It is recommended that function-like macros contain no more than 10 lines. -# 7 Variables +# 7 Variables In C language coding, variables are the most important except for functions. -When using a variable, you should always follow the principle of "single responsibility". + +When using a variable, you should always follow the principle of "single responsibility". + By scope, variables can be classified into global variables and local variables. -## Global Variables +## Global Variables + +Do not use or avoid using global variables. -Do not use or avoid using global variables. In program design, global variables are variables that are accessible to all scopes. Using unnecessary global variables is generally considered a bad habit. Disadvantages of global variables: @@ -1852,16 +1932,18 @@ Disadvantages of global variables: If unavoidable, the read and write of global variables should be encapsulated in a centralized manner. -### Rule 7.1 Do not use global variables as interfaces between modules. +### Rule 7.1 Do not use global variables as interfaces between modules. Global variables are for the internal implementation of modules and should not be exposed as interfaces. + Global variables should be as centralized as possible. If the data of this module needs to be disclosed to external modules, a function as an interface to this data should be provided. -## Local Variables +## Local Variables + +### Rule 7.2 Do not use uninitialized variables as rvalues. -### Rule 7.2 Do not use uninitialized variables as rvalues. +The variable here refers to a local dynamic variable, and also includes a memory block obtained on a memory heap. -The variable here refers to a local dynamic variable, and also includes a memory block obtained on a memory heap. Because their initial values are unpredictable, it is prohibited to use them directly as rvalues without effective initialization. ```c @@ -1887,12 +1969,15 @@ void Foo(...) } ``` -Uninitialized rvalues can be found by generic static check tools. +Uninitialized rvalues can be found by generic static check tools. + For example, the PCLint tool reports a warning for the following two examples. -> Warning 530: Symbol 'data' (line ...) not initialized Warning 644: Variable 'data' (line ...) may not have been initialized +> Warning 530: Symbol 'data' (line ...) not initialized +> +> Warning 644: Variable 'data' (line ...) may not have been initialized -### Rule 7.3 Forbid invalid and redundant variable initialization. +### Rule 7.3 Forbid invalid and redundant variable initialization. If the initial value is not determined before initialization is performed, it is not concise or secure and may cause problems that are more difficult to discover. @@ -1939,41 +2024,53 @@ void Foo(...) ``` In the preceding code, if 0 is not assigned before initialization, the static check tool can help find the problem of "direct use without being initialized". + However, due to invalid initialization, the defect of placing "UseData" before "GetData" cannot be easily found. Therefore, simple code should be written to initialize variables or memory blocks as required. The C99 does not limit the definition position of local variables to before the first statement in a function. That is, a variable can now be defined close to a variable. + This concise approach not only limits the scope of the variable scope, but also solves the problem of how to initialize the variable when it is defined. + If this compilation environment is supported, you are advised to define local variables in this way. **Exceptions:** + **As 'Secure Coding Standard' required, pointers, resource variables, and boolean variables can be treated as exceptions of this rule.** -### Rule 7.4 Do not use magic numbers. +### Rule 7.4 Do not use magic numbers. + +The so-called magic numbers are the numbers that are unintelligible and difficult to understand. -The so-called magic numbers are the numbers that are unintelligible and difficult to understand. The magic number is not a concept that can be defined literally. It varies depending on context and service knowledge. -For example, the number 12 varies in different contexts. -`type = 12;` is not intelligible, but `month = year * 12;` can be understood. +For example, the number 12 varies in different contexts. + +`type = 12;` is not intelligible, but `month = year * 12;` can be understood. + The number 0 is sometimes seen as a magic number. For example, the `status = 0;` cannot truly express any status information. -Solution: -Comments can be added for numbers that are used only once. +Solution: + +Comments can be added for numbers that are used only once. + For numbers that are used multiple times, macro or const variables must be defined and self-commented with symbolic naming. -The following cases are forbidden: -The name is not used to explain the meaning of a number, for example, `#define ZERO 0`. +The following cases are forbidden: + +The name is not used to explain the meaning of a number, for example, `#define ZERO 0`. + The value is limited by the name, for example, `#define XX_TIMER_INTERVAL_300MS 300`. -# 8 Programming Practice +# 8 Programming Practice -## Expressions +## Expressions -### Rec 8.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. +### Rec 8.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. + +When a variable is compared with a constant, placing the constant on the left, for example, `if (MAX == v)` does not read naturally, and `if (MAX > v)` is more difficult to understand. -When a variable is compared with a constant, placing the constant on the left, for example, `if (MAX == v)` does not read naturally, and `if (MAX > v)` is more difficult to understand. The constant should be placed on the right according to the normal reading order and habit. The expression is written as follows: ```c @@ -1985,9 +2082,10 @@ There are special cases: for example, the expression `if (MIN < v && v < MAX)` i You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. -### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. +### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. In an expression containing a variable increment or decrement operator, if the variable is referenced again, the result is not explicitly defined in the C standard, which may vary between compilers or different compiler versions. + For better portability, you should not make any assumptions about the operation sequence not defined in any standards. Note that this problem cannot be solved by using parentheses because it is not a problem of priority. @@ -2018,9 +2116,10 @@ i++; // Good: Single line. x = Func(i, i); ``` -### Rec 8.2 Use parentheses to specify the sequence of expressions, instead of using the default priority. +### Rec 8.2 Use parentheses to specify the sequence of expressions, instead of using the default priority. Parentheses can be used to better emphasize the purpose of used operators. This will prevent program errors due to the inconsistency between default priority and the intended design. + However, too many parentheses muddy the code, reducing readability. Use them moderately. Parentheses are recommended when expressions contain operators that are not commonly used and are confusing, such as bitwise operators. @@ -2029,14 +2128,16 @@ Parentheses are recommended when expressions contain operators that are not comm c = (a & 0xFF) + b; /* Parentheses are required while using bit operators. */ ``` -## Statements +## Statements -### Rule 8.2 Provide a 'default' branch for the `switch` statement. +### Rule 8.2 Provide a 'default' branch for the `switch` statement. In most cases, the 'default' branch exists in the switch statement to ensure that there is a default processing action when the case tag is missing. Exceptions: -If the switch condition variable is of the enum type and the case branches cover all values, then the default branch is redundant. + +If the switch condition variable is of the enum type and the case branches cover all values, then the default branch is redundant. + A modern compiler can check whether the case branch of some enumerated values is missing in the switch statement. A warning will be displayed. ```c @@ -2057,11 +2158,12 @@ switch (color) { } ``` -### Rec 8.3 Exercise caution when using the `goto` statement. +### Rec 8.3 Exercise caution when using the `goto` statement. The `goto` statement destroys the program. Avoid using it if possible. You can only jump to statements following the `goto` statement, and only within the one function. The `goto` statement is used to implement function return to a single point within a function. + If a function has a large number of identical logics that cannot be encapsulated, for example, repeated file execution, the processed part of code after the file operation failure (for example, closing the file handle and releasing memory that is dynamically applied for) is usually placed in the last part of the function body. And the goto statement is placed right before these. In this way, the code becomes clear and concise. It can also be encapsulated in functions or macros, but doing so makes code less straightforward. Example: @@ -2106,9 +2208,9 @@ EXIT: } ``` -## Type Conversion +## Type Conversion -### Rec 8.4 Minimize unnecessary type conversion and forced conversion. +### Rec 8.4 Minimize unnecessary type conversion and forced conversion. When the data type is forcibly changed, the meaning of the data and the value after conversion may change. If details are not considered, potential risks may be generated. diff --git a/en/contribute/code-of-conduct.md b/en/contribute/code-of-conduct.md index 6eea0059c3d2d38781a6d251bab7f639fe297fcd..09ba997e09eb252f1b30fd14cb63897658abf11e 100755 --- a/en/contribute/code-of-conduct.md +++ b/en/contribute/code-of-conduct.md @@ -1,4 +1,4 @@ -# Code of Conduct +# Code of Conduct The OpenHarmony community complies with the code of conduct specified in [Contributor Covenant](https://contributor-covenant.org/) of the open source community. For details, see [https://www.contributor-covenant.org/version/1/4/code-of-conduct/](https://www.contributor-covenant.org/version/1/4/code-of-conduct/). diff --git a/en/contribute/how-to-contribute.md b/en/contribute/how-to-contribute.md index 0e1f8ab9365b1a7f8c3c299992d6a816b02c89b6..1ee14278b36d16978cd1bfc61c8d98abc7538f34 100644 --- a/en/contribute/how-to-contribute.md +++ b/en/contribute/how-to-contribute.md @@ -1,8 +1,8 @@ -# How to Contribute +# How to Contribute -## Contributing Code +## Contributing Code -## Before You Start +## Before You Start **Signing the Developer Certificate of Origin** @@ -12,25 +12,25 @@ Click [here](https://dco.openharmony.cn/#/sign) to sign the DCO, and click [here **Code of Conduct** -OpenHarmony is an open source community that relies entirely on the friendly, welcoming environment of the community. Read and abide by the community's [Code of Conduct](code-of-conduct.md#EN-US_TOPIC_0000001055368056) before contributing to the community. +OpenHarmony is an open source community that relies entirely on the friendly, welcoming environment of the community. Read and abide by the community's [Code of Conduct](code-of-conduct.md) before contributing to the community. ## **Finding the SIG Group You Are Interested** For details about how to participate in Special Interest Group (SIG), see **SIG Governance**. -## Starting Contributing +## Starting Contributing -For details about how to contribute to code, see [Code Contributing ](code-contribution.md). +For details about how to contribute to code, see [Code Contributing ](code-contribution.md). ## Auto-Test For details about how to develop test cases based on test requirements, see [Test Subsystem](../readme/test.md). -## Contributing Documents +## Contributing Documents -For details, see [Documentation Contribution](documentation-contribution.md). +For details, see [Documentation Contribution](documentation-contribution.md). -## Communication in Community +## Communication in Community -For details, see [Communication in Community](communication-in-community.md#EN-US_TOPIC_0000001054608107). +For details, see [Communication in Community](communication-in-community.md). diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md index 730e34660723b900e84861fa40e0df1fb8f144e9..3b165dfeb546f502ee80c91c0d034549d2c5006d 100644 --- a/en/contribute/template/js-template.md +++ b/en/contribute/template/js-template.md @@ -96,7 +96,7 @@ import call from '@ohos.telephony.call'; | Name | Type | Readable| Writable| Description | | ---------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------ | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | +| pluggedType | [BatteryPluggedType]\(#batterypluggedtype) | Yes | No | Charger type of the current device. | | isBatteryPresent | boolean | Yes | No | Whether the battery is supported or present.| ## Methods @@ -270,7 +270,7 @@ The following is an example of the custom type of a key-value pair. | Name | Type | Readable| Writable| Description | | ------------ | ------------------- | ---- | ---- | ------------------------------------------------------------ | | parameterUrl | string | Yes | Yes | Media output URI. Supported:
1. Relative path whose protocol type is `internal`. Example:
Temporary directory: internal://cache/test.mp4
2. Absolute path. Example:
file:///data/data/ohos.xxx.xxx/files/test.mp4| -| parameterOne | [CustomEnum](#Enumeration)| Yes | Yes | Describe the attributes. The requirements are similar to those for the parameter description. | +| parameterOne | [CustomEnum](#enums) | Yes | Yes | Describe the attributes. The requirements are similar to those for the parameter description. | ## Change History | Change Description| Date| diff --git a/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md b/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md deleted file mode 100644 index 013f080c0dd6f0fb49f96ecf2cfa380290215f12..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md +++ /dev/null @@ -1,391 +0,0 @@ -# Photographing - -## When to Use - -Use the camera module APIs to capture frames \(photographing\). - -## Available APIs - -**Table 1** APIs for photographing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

Function

-

Description

-

CameraKit

-

int32_t GetCameraIds(std::list<string> cameraList)

-

Obtains IDs of cameras that are currently available.

-

CameraKit

-

CameraAbility& GetCameraAbility(string cameraId)

-

Obtains the camera capability

-

CameraKit

-

void RegisterCameraDeviceCallback(CameraDeviceCallback* callback, EventHandler* handler)

-

Registers a camera callback for camera status changes.

-

CameraKit

-

void UnregisterCameraDeviceCallback(CameraDeviceCallback* callback)

-

Unregisters a camera callback.

-

CameraKit

-

void CreateCamera(string cameraId, CameraStateCallback* callback, EventHandler* handler)

-

Creates a Camera instance.

-

Camera

-

string GetCameraId()

-

Obtains the camera ID.

-

Camera

-

CameraConfig& GetCameraConfig()

-

Obtains the camera configuration.

-

Camera

-

FrameConfig& GetFrameConfig(int32_t type)

-

Obtains the frame configuration.

-

Camera

-

void Configure(CameraConfig& config)

-

Configures the camera using the CameraConfig object.

-

Camera

-

void Release()

-

Releases the Camera object and associated resources.

-

Camera

-

int TriggerLoopingCapture(FrameConfig& frameConfig)

-

Starts looping-frame capture.

-

Camera

-

void StopLoopingCapture()

-

Stops looping-frame capture.

-

Camera

-

int32_t TriggerSingleCapture(FrameConfig& frameConfig)

-

Starts single-frame capture.

-

CameraConfig

-

void SetFrameStateCallback(FrameStateCallback* callback, EventHandler* handler);

-

Sets a frame state callback to respond to state changes.

-

CameraConfig

-

static CameraConfig* CreateCameraConfig()

-

Creates a CameraConfig instance.

-

CameraAbility

-

std::list<Size> GetSupportedSizes(int format)

-

Obtains the supported image sizes for a specified image format.

-

CameraAbility

-

std::list<T> GetParameterRange(uint32_t key)

-

Obtains the parameter value range based on a specified parameter key.

-

CameraDevice

-

CameraDeviceCallback()

-

A constructor used to create a CameraDeviceCallback instance.

-

CameraDevice

-

void OnCameraStatus​(std::string cameraId, int32_t status)

-

Called when the camera device status changes.

-

CameraStateCallback

-

CameraStateCallback​()

-

A constructor used to create a CameraStateCallback instance.

-

CameraStateCallback

-

void OnConfigured​(Camera& camera)

-

Called when the camera is configured.

-

CameraStateCallback

-

void OnConfigureFailed​(Camera& camera,int32_t errorCode)

-

Called when the camera fails to be configured.

-

CameraStateCallback

-

void OnCreated​(Camera& camera)

-

Called when the camera is successfully created.

-

CameraStateCallback

-

void OnCreateFailed​(std::string cameraId,int32_t errorCode)

-

Called when the camera fails to be created.

-

CameraStateCallback

-

void OnReleased​(Camera& camera)

-

Called when the camera is released.

-

FrameStateCallback

-

FrameStateCallback​()

-

A constructor used to create a FrameStateCallback instance.

-

FrameStateCallback

-

void OnFrameFinished(Camera& camera, FrameConfig& frameConfig, FrameResult& frameResult)

-

Called when the frame capture is completed.

-

FrameStateCallback

-

void OnFrameError​(Camera& camera, FrameConfig& frameConfig, int32_t errorCode, FrameResult& frameResult)

-

Called when the frame capture fails.

-

FrameConfig

-

int32_t GetFrameConfigType()

-

Obtains the frame configuration type.

-

FrameConfig

-

std::list<OHOS::Surface> GetSurfaces()

-

Obtains a list of surface objects (shared memories).

-

FrameConfig

-

void AddSurface(OHOS::AGP::UISurface& surface);

-

Adds a surface.

-

FrameConfig

-

void RemoveSurface(OHOS::AGP::UISurface& surface);

-

Removes a surface.

-
- -## Limitations and Constraints - -None - -## How to Develop - -1. Extend the **CameraDeviceCallback** class and call **OnCameraStatus** to customize operations when the camera device changes, for example, when a camera becomes available or unavailable. - - ``` - class SampleCameraDeviceCallback : public CameraDeviceCallback { - void OnCameraStatus(std::string cameraId, int32_t status) override - { - // Do something when camera is available or unavailable. - } - }; - ``` - -2. Extend the **FrameStateCallback** class. After obtaining the frame data, save the data as a file. - - ``` - static void SampleSaveCapture(const char *p, uint32_t size) - { - cout << "Start saving picture" << endl; - struct timeval tv; - gettimeofday(&tv, NULL); - struct tm *ltm = localtime(&tv.tv_sec); - if (ltm != nullptr) { - ostringstream ss("Capture_"); - ss << "Capture" << ltm->tm_hour << "-" << ltm->tm_min << "-" << ltm->tm_sec << ".jpg"; - - ofstream pic("/sdcard/" + ss.str(), ofstream::out | ofstream::trunc); - cout << "write " << size << " bytes" << endl; - pic.write(p, size); - cout << "Saving picture end" << endl; - } - } - - class TestFrameStateCallback : public FrameStateCallback { - void OnFrameFinished(Camera &camera, FrameConfig &fc, FrameResult &result) override - { - cout << "Receive frame complete inform." << endl; - if (fc.GetFrameConfigType() == FRAME_CONFIG_CAPTURE) { - cout << "Capture frame received." << endl; - list surfaceList = fc.GetSurfaces(); - for (Surface *surface : surfaceList) { - SurfaceBuffer *buffer = surface->AcquireBuffer(); - if (buffer != nullptr) { - char *virtAddr = static_cast(buffer->GetVirAddr()); - if (virtAddr != nullptr) { - SampleSaveCapture(virtAddr, buffer->GetSize()); - } - surface->ReleaseBuffer(buffer); - } - delete surface; - } - delete &fc; - } - } - }; - ``` - -3. Extend the **CameraStateCallback** class and customize operations when the camera state changes \(configuration successful or failed, and creation successful or failed\). - - ``` - class SampleCameraStateMng : public CameraStateCallback { - public: - SampleCameraStateMng() = delete; - SampleCameraStateMng(EventHandler &eventHdlr) : eventHdlr_(eventHdlr) {} - ~SampleCameraStateMng() - { - if (recordFd_ != -1) { - close(recordFd_); - } - } - void OnCreated(Camera &c) override - { - cout << "Sample recv OnCreate camera." << endl; - auto config = CameraConfig::CreateCameraConfig(); - config->SetFrameStateCallback(&fsCb_, &eventHdlr_); - c.Configure(*config); - cam_ = &c; - } - void OnCreateFailed(const std::string cameraId, int32_t errorCode) override {} - void OnReleased(Camera &c) override {} - }; - ``` - -4. Create a **CameraKit** instance to set and obtain camera information. - - ``` - CameraKit *camKit = CameraKit::GetInstance(); - list camList = camKit->GetCameraIds(); - string camId; - for (auto &cam : camList) { - cout << "camera name:" << cam << endl; - const CameraAbility *ability = camKit->GetCameraAbility(cam); - /* Find the camera that fits your ability. */ - list sizeList = ability->GetSupportedSizes(0); - if (find(sizeList.begin(), sizeList.end(), CAM_PIC_1080P) != sizeList.end()) { - camId = cam; - break; - } - } - ``` - -5. Create a **Camera** instance. - - ``` - EventHandler eventHdlr; // Create a thread to handle callback events. - SampleCameraStateMng CamStateMng(eventHdlr); - - camKit->CreateCamera(camId, CamStateMng, eventHdlr); - ``` - -6. Based on the callback design in steps 1 to 3, perform related operations until the **OnCreated** callback obtains **cam\_**. - - ``` - void OnCreated(Camera &c) override - { - cout << "Sample recv OnCreate camera." << endl; - auto config = CameraConfig::CreateCameraConfig(); - config->SetFrameStateCallback(&fsCb_, &eventHdlr_); - c.Configure(*config); - cam_ = &c; - } - - void Capture() - { - if (cam_ == nullptr) { - cout << "Camera is not ready." << endl; - return; - } - FrameConfig *fc = new FrameConfig(FRAME_CONFIG_CAPTURE); - Surface *surface = Surface::CreateSurface(); - if (surface == nullptr) { - delete fc; - return; - } - surface->SetWidthAndHeight(1920, 1080); /* 1920:width,1080:height */ - fc->AddSurface(*surface); - cam_->TriggerSingleCapture(*fc); - } - ``` - - diff --git a/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md b/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md deleted file mode 100644 index 96afe8a9d7a728e705e56b803619f02e95c4be9b..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md +++ /dev/null @@ -1,38 +0,0 @@ -# Video Recording - -## When to Use - -Use the camera module APIs to capture video streams. - -## Available APIs - -For details, see the available APIs described in development guidelines on photographing. - -## Limitations and Constraints - -None - -## How to Develop - -1. Perform step 1 through step 4 described in development guidelines on photographing. -2. Obtain the **FrameConfig** instance for audio recording. - - ``` - /* Obtain the surface from the recorder. */ - Surface *surface = recorder_->GetSurface(0); - surface->SetWidthAndHeight(1920, 1080); - surface->SetQueueSize(3); - surface->SetSize(1024 * 1024); - /* Add the surface to the FrameConfig instance. */ - FrameConfig *fc = new FrameConfig(FRAME_CONFIG_RECORD); - fc->AddSurface(*surface); - ``` - -3. Start and stop video recording. - - ``` - stateCallback->camera_->TriggerLoopingCapture(*fc); // Start recording. - stateCallback->camera_->StopLoopingCapture(); // Stop recording. - ``` - - diff --git a/en/device-dev/guide/device-iotcamera-control-example.md b/en/device-dev/guide/device-iotcamera-control-example.md deleted file mode 100644 index e13ad94f9036eba83d7d9bf157d72dbe127a3d6a..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-example.md +++ /dev/null @@ -1,45 +0,0 @@ -# Use Case - -- For details about the development board, compilation, burning, and image running, see [Quick Start](../quick-start/Readme-EN.md). A compilation result file of sample code is stored in **out/ipcamera\_hi3518ev300/dev\_tools/bin/camera\_sample**. You can copy the file to a TF card, or modify the compilation script of **camera\_sample** to copy the result to **rootfs.img**. - - Modify **output\_dir** in **applications/sample/camera/media/BUILD.gn**. - - - Before: **output\_dir = "$root\_out\_dir/dev\_tools"** - - After: **output\_dir = "$root\_out\_dir/"** - - Recompile the source code repository and burn the code into the development board. Then you can find the **camera\_sample** file in the **bin** directory of the board. - -- The sample code for camera development is stored in **applications/sample/camera/media/camera\_sample.cpp**. - - >![](../public_sys-resources/icon-notice.gif) **NOTICE:** - >You should insert a TF card \(maximum capacity: 128 GB\) for photographing and video recording functions. After the system is started, the TF card is automatically mounted to the **/sdcard** directory. If the TF card is inserted after the system is started, you have to manually mount the TF card. To view the photos and videos in the TF card, copy the content to a computer. The preview function does not require a TF card. - - -1. Run the **cd** command to go to the end path of the executable program and start **camera\_sample** by running the command in the following figure. - - **Figure 1** Starting camera\_sample - ![](figures/starting-camera_sample.png "starting-camera_sample") - - The control commands are displayed as shown in the preceding figure. Press **S** to stop the current operation \(including video recording and preview\), and press **Q** to exit the program. - -2. Press **1** to take a photo in JPG format. The photo is saved in the **/sdcard** directory and named **Capture\***. - - **Figure 2** Serial port logs displayed after the photographing command is executed - ![](figures/serial-port-logs-displayed-after-the-photographing-command-is-executed.png "serial-port-logs-displayed-after-the-photographing-command-is-executed") - - To view the saved file, exit the program and enter the file system. To start the program again, return to the previous step. - - **Figure 3** Saved files - ![](figures/saved-files.png "saved-files") - -3. Press **2** to start recording. The video file is in MP4 format and saved in the **/sdcard** directory with the name **Record\***. Press **S** to stop recording. - - **Figure 4** Serial port logs displayed after the recording command is executed - ![](figures/serial-port-logs-displayed-after-the-recording-command-is-executed.png "serial-port-logs-displayed-after-the-recording-command-is-executed") - -4. Press **Q** to exit. - - **Figure 5** Serial port logs displayed after the exit command is executed - ![](figures/serial-port-logs-displayed-after-the-exit-command-is-executed.png "serial-port-logs-displayed-after-the-exit-command-is-executed") - - diff --git a/en/device-dev/guide/device-iotcamera-control-overview.md b/en/device-dev/guide/device-iotcamera-control-overview.md deleted file mode 100644 index d67f97231ed8c18469818d1d0e1c43cb69ab1141..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-overview.md +++ /dev/null @@ -1,10 +0,0 @@ -# Camera Control Overview - -This document describes how to use the IoT camera development board and the built-in camera of the development kit to implement photographing and video recording. - -You can perform operations provided in [Use Case](device-iotcamera-control-example.md) to learn more about development board peripheral control and then develop devices such as cameras. - -If you want to view the sample effect first, see [Use Case](device-iotcamera-control-example.md). To customize application behavior, modify the sample code by referring to APIs described in the next section. - -For details about basic concepts for camera development, see [Camera Overview](../subsystems/subsys-multimedia-camera-overview.md). - diff --git a/en/device-dev/kernel/kernel-mini-appx-code.md b/en/device-dev/kernel/kernel-mini-appx-code.md index 715a5dd6f51a7e148341489d8e55f4e176862ca4..188d3da02f28bc9174eb39e15f2e5219e2baca2b 100644 --- a/en/device-dev/kernel/kernel-mini-appx-code.md +++ b/en/device-dev/kernel/kernel-mini-appx-code.md @@ -1,4 +1,4 @@ -# Kernel Coding Specification +# Kernel Coding Specification This kernel coding specification is developed based on the general programming specifications in the industry. It defines the programming styles for kernel developers to follow. diff --git a/en/device-dev/kernel/kernel-mini-overview.md b/en/device-dev/kernel/kernel-mini-overview.md index 14143821f6515d56893e029baf1d82e564ee816e..eac632e65f4e4b00a81bc8c0b77ce653288fc77e 100644 --- a/en/device-dev/kernel/kernel-mini-overview.md +++ b/en/device-dev/kernel/kernel-mini-overview.md @@ -24,7 +24,7 @@ The CPU architecture includes two layers: general architecture definition layer | Header file name| los_<function>.h | los_arch_<function>.h | | Function name| Halxxxx | Halxxxx | -LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. If you need to expand the CPU architecture, see [Chip Architecture Adaptation](../porting/porting-chip-kernel-overview.md). +LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. ## Working Principles diff --git a/en/device-dev/porting/figures/architecture-of-the-liteos-cortex-m-kernel.png b/en/device-dev/porting/figures/architecture-of-the-liteos-cortex-m-kernel.png new file mode 100644 index 0000000000000000000000000000000000000000..ec5d0c84f2e33378bb3db863d595b128d186d96a Binary files /dev/null and b/en/device-dev/porting/figures/architecture-of-the-liteos-cortex-m-kernel.png differ diff --git a/en/device-dev/porting/porting-chip-kernel-overview.md b/en/device-dev/porting/porting-chip-kernel-overview.md index 00c50ec8944875ca6491391b25d12574906f792e..09385503b4450a85a55ecf7dd371d6db4bca6535 100644 --- a/en/device-dev/porting/porting-chip-kernel-overview.md +++ b/en/device-dev/porting/porting-chip-kernel-overview.md @@ -16,7 +16,7 @@ The kernel used by module chips is LiteOS Cortex-M, which consists of four modul **Figure 1** Architecture of the LiteOS Cortex-M kernel - +![architecture-of-the-liteos-cortex-m-kernel.png](figures/architecture-of-the-liteos-cortex-m-kernel.png) The directory structure of the kernel is described as follows: diff --git a/en/device-dev/security/security-guidelines-overall.md b/en/device-dev/security/security-guidelines-overall.md index 8c551e4d29637b69eb9d81437eb5360e87bad324..e3c6685ab0b5052b7e15780e0c1f45381e9479cc 100644 --- a/en/device-dev/security/security-guidelines-overall.md +++ b/en/device-dev/security/security-guidelines-overall.md @@ -94,7 +94,7 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom - Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade (if available) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade. -## Data security +## Data Security ### Security Mechanism diff --git a/en/device-dev/security/security-privacy-protection.md b/en/device-dev/security/security-privacy-protection.md index 71557e17c7a2dde14fba1752b0fcb9d0b0d1b853..334f54d53554bd63054b2531de815f077db96e06 100644 --- a/en/device-dev/security/security-privacy-protection.md +++ b/en/device-dev/security/security-privacy-protection.md @@ -1,6 +1,6 @@ -# Privacy Protection +# Privacy Protection -## Overview +## Overview Personal data plays an increasingly important role in social economy and daily life along with the development of the Internet and informatization. Meanwhile, personal data leakage risks are increasing. As consumer product developers, you shall take more effective measures to protect users' personal data and improve their trust in your products. To protect consumers' privacy and improve their experience on privacy, you should set high-level privacy protection policies for your product. @@ -49,7 +49,7 @@ Personal data plays an increasingly important role in social economy and daily l - Users provide information proactively, such as scenarios where a user enters their identification number and bank card number to bind the bank card. -## Data Classification +## Data Classification Data is classified into five levels: very high, high, moderate, low, and public based on the data protection objectives and consequences \(the impact of legal risks caused by data leakage or damage on individuals, organizations, or the public\). @@ -116,7 +116,7 @@ Data is classified into five levels: very high, high, moderate, low, and public Note: For details about the definitions of privacy protection and data classification, see GDPR. -## General Privacy Design Rules +## General Privacy Design Rules To help you better complete privacy design for OpenHarmony products, we sort out general privacy design requirements. @@ -133,7 +133,7 @@ When collecting personal data, clearly and explicitly notify users of the data t Guided by the preceding principles, we have designed some examples for your reference. The figures below are examples of a privacy notice and a privacy statement, respectively. - **Figure 1** Examples of a privacy notice and a privacy statement + **Figure 1** Examples of a privacy notice and a privacy statement ![](figure/privacy-notice.png)![](figure/privacy-statement.png) @@ -190,9 +190,9 @@ You shall obtain consent from users and comply with applicable laws and regulati Data processing security shall be ensured in technical terms, which include encrypted data storage and secure data transfer. Security mechanisms or measures shall be enabled by default for a system. -- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication \(such as username and password\) allows only authenticated users to access data in multi-user scenarios. Access control \(for example, [permission control](security-guidelines-overall.md#section852593153614)\) can be applied to restrict access to applications. +- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication \(such as username and password\) allows only authenticated users to access data in multi-user scenarios. Access control \(for example, [permission control](../security/security-guidelines-overall.md)\) can be applied to restrict access to applications. - Secure storage of personal data on distributed devices must meet Huawei Universal Keystore \(HUKS\) requirements, including secure storage of keys and data. -- The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Security Guidelines](security-guidelines-overall.md#section26153183616). +- The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Device Interconnection Security](../security/security-guidelines-overall.md#device-interconnection-security). - Authentication data \(such as passwords and fingerprints\) shall be encrypted before being stored. **Localization** @@ -203,7 +203,7 @@ User data shall be preferentially processed on the local device. Data that canno If your product is designed for minors or you can identify, based on the collected user age data, that the end user is a minor, you shall particularly analyze issues related to minors' personal data protection based on relevant national laws in the target market. Your product shall obtain explicit consent from the holders of parental responsibility over minors. -## **Privacy Protection Requirements for Special Categories** +## **Privacy Protection Requirements for Special Categories** In addition to these general privacy requirements, consumer hardware products have the following requirements for special categories. You shall comply with these requirements during product design. diff --git a/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md b/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md index 0a65ca9e584e80c6b1bf8662c85e8759b4711750..d1cca7c960f6e22ba52860f799b9fa3e2994338b 100644 --- a/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md +++ b/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md @@ -1,4 +1,4 @@ -# AI Framework Development Guide +# AI Framework Development ## **Overview** diff --git a/en/device-dev/subsystems/subsys-dfx-hitracechain.md b/en/device-dev/subsystems/subsys-dfx-hitracechain.md index 6639011302e78ba1e9931b24362c5790c24dd4a3..8e7ded998f75f6fde34134a1240486193431058d 100644 --- a/en/device-dev/subsystems/subsys-dfx-hitracechain.md +++ b/en/device-dev/subsystems/subsys-dfx-hitracechain.md @@ -1,10 +1,10 @@ -# HiTraceChain Development +# HiTraceChain Development -## Overview +## Overview HiTraceChain tracks the call chain with the same **traceid** throughout the inter-device, inter-process, and inter-thread service processes. It associates and displays the call relationship and various output information during the entire process, helping you analyze and locate faults and optimize the system. -## Use Cases +## Use Cases HiTraceChain can be used for the following purposes: @@ -14,32 +14,36 @@ HiTraceChain can be used for the following purposes: - Works with the IDE to debug the detailed service process and time consumption distribution for system optimization. - **Figure 1** Use cases of HiTraceChain + **Figure 1** Use cases of HiTraceChain + ![](figure/use-cases-of-hitrace.png "use-cases-of-hitrace") -### Usage Example +### Usage Example + +**Figure 2** Service calling process \(inter-device and inter-process synchronous call\) -**Figure 2** Service calling process \(inter-device and inter-process synchronous call\) ![](figure/service-calling-process-(inter-device-and-inter-process-synchronous-call).png "service-calling-process-(inter-device-and-inter-process-synchronous-call)") -1. Display the call relationship in the service process, analyze key paths and function dependency, and determine the time consumption and call frequency at each call point to detect performance bottlenecks. +1. Display the call relationship in the service process, analyze key paths and function dependency, and determine the time consumption and call frequency at each call point to detect performance bottlenecks. + + **Figure 3** Service calling process - **Figure 3** Service calling process - ![](figure/service-calling-process.png "service-calling-process") + ![](figure/service-calling-process.png "service-calling-process") - **Figure 4** Time delay in the service calling process - ![](figure/time-delay-in-the-service-calling-process.png "time-delay-in-the-service-calling-process") + **Figure 4** Time delay in the service calling process + + ![](figure/time-delay-in-the-service-calling-process.png "time-delay-in-the-service-calling-process") 2. Add **traceid** to logs and events automatically to facilitate comprehensive analysis and quick fault location. -## Available APIs +## Available APIs HiTraceChain provides C++ and C APIs. The upper-layer services mainly use HiTraceChain to start and stop call chain tracing. HiTraceChain is implemented at layer C. It works by transferring **traceid** throughout the service calling process. Before service processing, HiTraceChain sets **traceid** in the thread local storage \(TLS\) of the calling thread. During service processing, HiTraceChain obtains **traceid** from the contextual TLS of the calling thread and automatically adds it to the log and event information. After service processing is complete, HiTraceChain clears **traceid** from the TLS of the calling thread. -### Java, C++, and C APIs +### Java, C++, and C APIs **Table 1** Description of C++ and C APIs @@ -195,7 +199,7 @@ HiTraceChain is implemented at layer C. It works by transferring **traceid** t -### Parameters of C++ APIs +### Parameters of C++ APIs **Table 2** Parameters of C++ APIs @@ -428,7 +432,7 @@ HiTraceChain is implemented at layer C. It works by transferring **traceid** t -## Call Chain Processing +## Call Chain Processing Inter-device, inter-process, and inter-thread calls are implemented through the communication mechanism. **HiTraceChain** requires transfer of **traceid** in the communication mechanism. @@ -438,7 +442,8 @@ The following figure shows the process of transferring **traceid** in synchron Extended communication mechanisms can also follow this implementation. -**Figure 5** Call chain tracing in synchronous communication +**Figure 5** Call chain tracing in synchronous communication + ![](figure/call-chain-tracing-in-synchronous-communication.png "call-chain-tracing-in-synchronous-communication") The process is as follows: @@ -471,9 +476,9 @@ The process is as follows: 8. The service module on the client processes the transact reply response. 9. When the process ends, the service module on the client calls the **end\(\)** function to stop call chain tracing. -## How to Develop +## How to Develop -### C++ +### C++ 1. Develop the source code. @@ -499,7 +504,7 @@ The process is as follows: ``` -### C +### C 1. Develop the source code. diff --git a/en/device-dev/subsystems/subsys-tel-guide.md b/en/device-dev/subsystems/subsys-tel-guide.md index 9b204051bd6742a6cd6afbf550d67f8ac8186c9e..9ddc0393b11c42349822e2dbd1d30d8875d848c4 100644 --- a/en/device-dev/subsystems/subsys-tel-guide.md +++ b/en/device-dev/subsystems/subsys-tel-guide.md @@ -1,8 +1,8 @@ -# Telephony Development +# Telephony Development -## Initializing a Modem Vendor Library +## Initializing a Modem Vendor Library -### When to Use +### When to Use Initializing a modem vendor library means to implement **const HRilOps \*RilInitOps\(const struct HRilReport \*reportOps\)** function in the vendor library. This function is mainly used to: @@ -10,17 +10,17 @@ Initializing a modem vendor library means to implement **const HRilOps \*RilInit - Create a thread for reading modem nodes. In this thread, the data reported by the modem is read cyclically and parsed as a specific service event for reporting. - Return the function pointer of the service request API to RIL Adapter. -### Available APIs +### Available APIs The following table describes the API for initializing a modem vendor library. **Table 1** API for initializing a modem vendor library -| API | Description | +| API | Description | | -------- | -------- | -| const HRilOps \*RilInitOps(const struct HRilReport \* reportOps) | Provides an entry for running a modem vendor library.
Input parameter:
**reportOps**: Specifies the pointer to the event callback function, which is passed by RIL Adapter.
Return result: function pointer of the service request API. | +| const HRilOps \*RilInitOps(const struct HRilReport \* reportOps) | Provides an entry for running a modem vendor library.
Input parameter:
**reportOps**: Specifies the pointer to the event callback function, which is passed by RIL Adapter.
Return result: function pointer of the service request API. | -### How to Develop +### How to Develop 1. Set the event callback function pointers passed by RIL Adapter through **RilInitOps**. @@ -37,7 +37,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. Create the **g\_reader** main thread to enable message looping. +2. Create the **g\_reader** main thread to enable message looping. ``` pthread_attr_t t; @@ -47,7 +47,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. In the **g\_eventListeners** thread, use **open\(\)** to open a modem node and then create the **g\_reader** thread to read and process messages reported by the modem. +3. In the **g\_eventListeners** thread, use **open\(\)** to open a modem node and then create the **g\_reader** thread to read and process messages reported by the modem. ``` g_fd = open(g_devicePath, O_RDWR); // Open the device node specified by g_devicePath. @@ -57,7 +57,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. Return the function pointer of the service request API. +4. Return the function pointer of the service request API. ``` // Structure for the service request API of the call module @@ -105,9 +105,9 @@ The following table describes the API for initializing a modem vendor library. ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. For details about how to integrate a library file, see [Integrating Modem Vendor Libraries](#section590mcpsimp). +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. For details about how to integrate a library file, see [Integrating Modem Vendor Libraries](#integrating-modem-vendor-libraries). ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -128,24 +128,24 @@ The following table describes the API for initializing a modem vendor library. ``` -## Responding to Modem Service Requests +## Responding to Modem Service Requests -### When to Use +### When to Use After receiving a specific telephony service request, RIL Adapter calls the target function pointer obtained in modem vendor library initialization to send a specific service request to the vendor library. Then, the vendor library processes the request based on the request ID. -### Available APIs +### Available APIs The following table describes the APIs for responding to modem service requests, with the dial module as an example. **Table 2** APIs for responding to modem service requests -| API | Description | +| API | Description | | -------- | -------- | -| void ReqDial(ReqDataInfo \*requestInfo, const void \*data, size_t dataLen); | Processes number dial requests.
Input parameters:
**requestInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | -| void (\*OnCallReport)(struct ReportInfo reportInfo, const void \*data, size_t dataLen); | Reports the execution result of a service request to RIL Adapter.
Input parameters:
**reportInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | +| void ReqDial(ReqDataInfo \*requestInfo, const void \*data, size_t dataLen); | Processes number dial requests.
Input parameters:
**requestInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | +| void (\*OnCallReport)(struct ReportInfo reportInfo, const void \*data, size_t dataLen); | Reports the execution result of a service request to RIL Adapter.
Input parameters:
**reportInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | -### How to Develop +### How to Develop 1. Implement processing of dial requests in the **ReqDial\(\)** API. @@ -199,9 +199,9 @@ The following table describes the APIs for responding to modem service requests, ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -242,23 +242,23 @@ The following table describes the APIs for responding to modem service requests, ``` -## Reporting Modem Events +## Reporting Modem Events -### When to Use +### When to Use A modem node thread reads the messages reported by the modem cyclically, parses the messages into specific events, and then reports the events to RIL Adapter. -### Available APIs +### Available APIs The following table describes the API for reporting modem events. **Table 3** API for reporting modem events -| API | Description | +| API | Description | | -------- | -------- | -| void OnNotifyOps(const char \*s, const char \*smsPdu) | Distributes the events reported by the modem.
Input parameters:
**s**: AT command prefix
**smsPdu**: PDU of the SMS message
Return value: none | +| void OnNotifyOps(const char \*s, const char \*smsPdu) | Distributes the events reported by the modem.
Input parameters:
**s**: AT command prefix
**smsPdu**: PDU of the SMS message
Return value: none | -### How to Develop +### How to Develop 1. Call **OnNotifyOps\(\)** in the g\_reader thread of the modem device node to parse reported modem events. On determining the command type, call **OnXxxReport\(\)** to report the parsed module events to the hril layer. @@ -290,7 +290,7 @@ The following table describes the API for reporting modem events. ``` -1. Distribute the reported events from the **hril** layer to the Telephony Service layer. +2. Distribute the reported events from the **hril** layer to the Telephony Service layer. ``` // Report the call status proactively. @@ -316,9 +316,9 @@ The following table describes the API for reporting modem events. ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -370,18 +370,18 @@ The following table describes the API for reporting modem events. ``` -### Development Examples +### Development Examples - **Outgoing Call** The following figure shows the API calling for an outgoing call. **Figure 1** Time sequence of API calling for an outgoing call - + ![](figure/en-us_image_0000001171507146.png) - When an application initiates an outgoing call, RIL Adapter receives a call request, and the **hril** layer invokes the **ReqDial\(\)** function. In **ReqDial\(\)**, the data passed by the Telephony Service is encapsulated as an AT command and sent to the modem. After executing the dial command, the modem reports the execution result to RIL Adapter through **OnCallReport\(\)**. + When an application initiates an outgoing call, RIL Adapter receives a call request, and the **hril** layer invokes the **ReqDial\(\)** function. In **ReqDial\(\)**, the data passed by the Telephony Service is encapsulated as an AT command and sent to the modem. After executing the dial command, the modem reports the execution result to RIL Adapter through **OnCallReport\(\)**. ``` // Callback function pointer of the call module @@ -456,13 +456,13 @@ The following table describes the API for reporting modem events. The following figure shows the API calling of an incoming call. **Figure 2** Time sequence of API calling for an incoming call - + ![](figure/en-us_image_0000001214727595.png) - The **g\_reader** thread cyclically reads the messages reported by the modem. When the modem receives an incoming call event, it actively reports the information about the incoming call. + The **g\_reader** thread cyclically reads the messages reported by the modem. When the modem receives an incoming call event, it actively reports the information about the incoming call. - The **g\_reader** thread calls **OnNotifyOps\(\)** to parse the reported information. If the parsed data reported by the modem starts with characters such as **+CRING** or **RING**, it indicates that an incoming call event exists. In this case, the event is reported to RIL Adapter through **OnCallReport\(reportInfo, NULL, 0\)**. + The **g\_reader** thread calls **OnNotifyOps\(\)** to parse the reported information. If the parsed data reported by the modem starts with characters such as **+CRING** or **RING**, it indicates that an incoming call event exists. In this case, the event is reported to RIL Adapter through **OnCallReport\(reportInfo, NULL, 0\)**. ``` // Parse the data reported by the modem as events proactively reported by the corresponding module. @@ -492,11 +492,11 @@ The following table describes the API for reporting modem events. ``` -## Integrating Modem Vendor Libraries +## Integrating Modem Vendor Libraries -### Configuring Compilation Information +### Configuring Compilation Information -Compile the modem vendor library into a dynamic library by using **BUILD.gn**. Upon startup, RIL Adapter loads the dynamic library to the system in dlopen mode and then initializes the library. For details about how to implement vendor library initialization, see [Initializing a Modem Vendor Library](#section211mcpsimp). The following is an example of **BUILD.gn**: +Compile the modem vendor library into a dynamic library by using **BUILD.gn**. Upon startup, RIL Adapter loads the dynamic library to the system in dlopen mode and then initializes the library. For details about how to implement vendor library initialization, see [Initializing a Modem Vendor Library](#initializing-a-modem-vendor-library). The following is an example of **BUILD.gn**: ``` import("//build/ohos.gni") @@ -523,7 +523,7 @@ ohos_shared_library("ril_vendor") { // Modem vendor library } ``` -### Debugging and Verification +### Debugging and Verification 1. Compile the code. 2. Check whether **libril\_vendor.z.so** exists in the **/out/{device_name}/telephony/ril\_adapter** directory. If yes, the integration is successful. Otherwise, correct the error and perform debugging and verification again. diff --git a/en/device-dev/website.md b/en/device-dev/website.md index de8c53fb7d2a4714f6a2d1c3a1077013330eca24..6cfcbb65bcd6cf29218f11a58f8f67667d061f9c 100644 --- a/en/device-dev/website.md +++ b/en/device-dev/website.md @@ -395,6 +395,7 @@ - [Doubly Linked List](kernel/kernel-small-apx-dll.md) - [Bitwise Operation](kernel/kernel-small-apx-bitwise.md) - [Standard Library](kernel/kernel-small-apx-library.md) + - [Kernel Coding Specification](kernel/kernel-mini-appx-code.md) - Kernel for Standard Systems - [Linux Kernel Overview](kernel/kernel-standard-overview.md) - [Applying Patches on OpenHarmony Development Boards](kernel/kernel-standard-patch.md) @@ -450,6 +451,7 @@ - Peripheral Driver Usage - [Audio](driver/driver-peripherals-audio-des.md) - [Camera](driver/driver-peripherals-camera-des.md) + - [Codec](driver/driver-peripherals-codec-des.md) - [Facial Authentication](driver/driver-peripherals-face_auth-des.md) - [Fingerprint Authentication](driver/driver-peripherals-fingerprint_auth-des.md) - [LCD](driver/driver-peripherals-lcd-des.md) @@ -502,21 +504,7 @@ - [Utils Overview](subsystems/subsys-utils-overview.md) - [Utils Development](subsystems/subsys-utils-guide.md) - [Utils FAQ](subsystems/subsys-utils-faqs.md) - - AI Framework - - [AI Engine Framework](subsystems/subsys-aiframework-guide.md) - - [Development Environment](subsystems/subsys-aiframework-envbuild.md) - - Technical Specifications - - [Code Management](subsystems/subsys-aiframework-tech-codemanage.md) - - [Naming](subsystems/subsys-aiframework-tech-name.md) - - [API Development](subsystems/subsys-aiframework-tech-interface.md) - - Development Guidelines - - [SDK](subsystems/subsys-aiframework-devguide-sdk.md) - - [Plug-in](subsystems/subsys-aiframework-devguide-plugin.md) - - [Configuration File](subsystems/subsys-aiframework-devguide-conf.md) - - Development Examples - - [KWS SDK](subsystems/subsys-aiframework-demo-sdk.md) - - [KWS Plug-in](subsystems/subsys-aiframework-demo-plugin.md) - - [KWS Configuration File](subsystems/subsys-aiframework-demo-conf.md) + - [AI Framework Development](subsystems/subsys-ai-aiframework-devguide.md) - Data Management - RDB - [RDB Overview](subsystems/subsys-data-relational-database-overview.md) @@ -547,7 +535,7 @@ - [Development on Application Permission Management](subsystems/subsys-security-rightmanagement.md) - [Development on IPC Authentication](subsystems/subsys-security-communicationverify.md) - [Development on Device Security Level Management](subsystems/subsys-security-devicesecuritylevel.md) - + - [Development on HUKS](subsystems/subsys-security-huks-guide.md) - Startup - [Startup](subsystems/subsys-boot-overview.md) - init Module @@ -561,11 +549,11 @@ - [bootstrap Module](subsystems/subsys-boot-bootstrap.md) - [FAQs](subsystems/subsys-boot-faqs.md) - [Reference](subsystems/subsys-boot-ref.md) - - DFX +- DFX - [DFX](subsystems/subsys-dfx-overview.md) - [HiLog Development](subsystems/subsys-dfx-hilog-rich.md) - [HiLog\_Lite Development](subsystems/subsys-dfx-hilog-lite.md) - - [HiTrace Development](subsystems/subsys-dfx-hitrace.md) + - [HiTraceChain Development](subsystems/subsys-dfx-hitracechain.md) - [HiCollie Development](subsystems/subsys-dfx-hicollie.md) - HiSysEvent Development - [HiSysEvent Logging Configuration](subsystems/subsys-dfx-hisysevent-logging-config.md) @@ -577,7 +565,7 @@ - [HiChecker Development](subsystems/subsys-dfx-hichecker.md) - [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md) - [Hiview Development](subsystems/subsys-dfx-hiview.md) - + - Featured Topics - HPM Part - [HPM Part Overview](hpm-part/hpm-part-about.md) @@ -592,13 +580,6 @@ - WLAN-connected Products - [LED Peripheral Control](guide/device-wlan-led-control.md) - [Third-Party SDK Integration](guide/device-wlan-sdk.md) - - Cameras Without a Screen - - Camera Control - - [Overview](guide/device-iotcamera-control-overview.md) - - Development Guidelines - - [Photographing](guide/device-iotcamera-control-demo-photodevguide.md) - - [Video Recording](guide/device-iotcamera-control-demo-videodevguide.md) - - [Use Case](guide/device-iotcamera-control-example.md) - Cameras with a Screen - Screen and Camera Control - [Overview](guide/device-camera-control-overview.md) @@ -643,11 +624,7 @@ - [Kernel](faqs/faqs-kernel.md) - [Porting](faqs/faqs-porting.md) - [Startup](faqs/faqs-startup.md) - - [System Applications](faqs/faqs-system-applications.md) - - - - + - [System Applications](faqs/faqs-system-applications.md) diff --git a/en/readme/ai.md b/en/readme/ai.md index 2bf316a7650c1767088ad9be877ac5a20f5ccfb1..9115a0024e450acd7a74f151bba0cda4db2c9841 100644 --- a/en/readme/ai.md +++ b/en/readme/ai.md @@ -1,13 +1,13 @@ -# AI +# AI -## Introduction +## Introduction The AI subsystem is the part of OpenHarmony that provides native distributed AI capabilities. At the heart of the subsystem is a unified AI engine framework, which implements quick integration of AI algorithm plug-ins. The framework consists of the plug-in management, module management, and communication management modules, fulfilling lifecycle management and on-demand deployment of AI algorithms. Under this framework, AI algorithm APIs will be standardized to facilitate distributed calling of AI capabilities. In addition, unified inference APIs will be provided to adapt to different inference framework hierarchies. **Figure 1** AI engine framework ![](figures/ai-engine-framework.png "ai-engine-framework") -## Directory Structure +## Directory Structure ``` /foundation/ai/engine # Home directory of the AI subsystem @@ -32,7 +32,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI │ │ └── server_executor # Executor of the server module ``` -## Constraints +## Constraints * **Programming language**: C/C++ @@ -40,7 +40,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI * **Others**: The System Ability Manager \(Samgr\) has been started and is running properly. -## Usage +## Usage 1. Compile the AI subsystem. @@ -406,7 +406,7 @@ The AI subsystem is the part of OpenHarmony that provides native distributed AI ``` -## Repositories Involved +## Repositories Involved [AI subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/ai.md) @@ -420,8 +420,8 @@ Dependency repositories: [startup\_init\_lite](https://gitee.com/openharmony/startup_init_lite/blob/master/README.md) -## Reference +## Reference -[AI Engine Framework Development Guide](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-aiframework-guide.md) +[AI Framework Development](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md) diff --git a/en/readme/figures/en-us_image_0000001124735133.png b/en/readme/figures/en-us_image_0000001124735133.png deleted file mode 100644 index c64f96cea56de84488971282f1e3d96b4fa264a6..0000000000000000000000000000000000000000 Binary files a/en/readme/figures/en-us_image_0000001124735133.png and /dev/null differ diff --git a/en/readme/figures/multimedia-service-flow-for-the-small-system.png b/en/readme/figures/multimedia-service-flow-for-the-small-system.png deleted file mode 100755 index 0fac47fbc29296ecdf9078be5e0fa2b6c85617c7..0000000000000000000000000000000000000000 Binary files a/en/readme/figures/multimedia-service-flow-for-the-small-system.png and /dev/null differ diff --git a/en/readme/figures/multimedia-subsystem-architecture.png b/en/readme/figures/multimedia-subsystem-architecture.png deleted file mode 100755 index 356a90cd32d5e48960eb6b02c964b761a8d3b380..0000000000000000000000000000000000000000 Binary files a/en/readme/figures/multimedia-subsystem-architecture.png and /dev/null differ diff --git a/en/readme/startup.md b/en/readme/startup.md index 4d1d1780815533373ea44576ea746c119625d80d..5f12643fffc97c3a896d8fe918dde75a4e9c91a6 100644 --- a/en/readme/startup.md +++ b/en/readme/startup.md @@ -1,6 +1,6 @@ -# Startup +# Startup -## Introduction +## Introduction The startup subsystem is responsible for starting key system processes and services after the kernel is started and before applications are started. The subsystem consists of the following modules: @@ -8,7 +8,7 @@ The startup subsystem is responsible for starting key system processes and servi This module can be used on platforms powered by LiteOS Cortex-A or Linux kernel. - The module starts system service processes from the time the kernel loads the first user-space process to the time the first application is started. In addition to loading key system processes, it needs to configure their permissions during the startup and keep the specified process alive after sub-processes are started. If a key process exits abnormally, the module needs to perform a system restart. For details, see [init Module](../device-dev/subsystems/subsys-boot-init.md). + The module starts system service processes from the time the kernel loads the first user-space process to the time the first application is started. In addition to loading key system processes, it needs to configure their permissions during the startup and keep the specified process alive after sub-processes are started. If a key process exits abnormally, the module needs to perform a system restart. For details, see [init Module](../device-dev/subsystems/subsys-boot-init-cfg.md). - appspawn @@ -27,58 +27,22 @@ The startup subsystem is responsible for starting key system processes and servi This module obtains and sets system attributes. - The module can be used on all platforms. Supported system attributes consist of default, OEM-specified, and custom system attributes. OEM-specified system attributes provide only default values. The specific values need to be adjusted as required. For details, see [syspara Module](../device-dev/subsystems/subsys-boot-syspara.md). + The module can be used on all platforms. Supported system attributes consist of default, OEM-specified, and custom system attributes. OEM-specified system attributes provide only default values. The specific values need to be adjusted as required. For details, see [syspara Module](../device-dev/subsystems/subsys-boot-init-sysparam.md). -## Directory Structure +## Directory Structure **Table 1** Directory structure of the source code for the startup subsystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Directory

-

Description

-

Applicable Platform

-

base/startup/appspawn_lite

-

appspawn module of the Lite edition for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them.

-
Platforms using the LiteOS Cortex-A kernel -

base/startup/appspawn_standard

-

appspawn module of the Standard version for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them.

-
Platforms using the Linux kernel -

base/startup/bootstrap_lite

-

bootstrap module for starting all services except core system services.

-
Platforms using the LiteOS Cortex-M kernel -

base/startup/init_lite

-

init_lite module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them.

-
Platforms using the LiteOS Cortex-A or Linux kernel

base/startup/syspara_lite

-

syspara module that provides APIs to obtain device information, including the product name, brand name, category name, and manufacturer name.

-
All platforms
+| Directory | Description | Applicable Platform | +| ------------------------------ | ------------------------------------------------------------ | --------------------------------------------------- | +| base/startup/appspawn_lite | appspawn module of the Lite edition for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the LiteOS Cortex-A kernel | +| base/startup/appspawn_standard | appspawn module of the Standard version for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the Linux kernel | +| base/startup/bootstrap_lite | bootstrap module for starting all services except core system services. | Platforms using the LiteOS Cortex-M kernel | +| base/startup/init_lite | init_lite module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them. | Platforms using the LiteOS Cortex-A or Linux kernel | +| base/startup/syspara_lite | syspara module that provides APIs to obtain device information, including the product name, brand name, category name, and manufacturer name. | All platforms | + + ``` @@ -111,7 +75,7 @@ base/startup/ └── simulator # Simulator adaptation ``` -## Repositories Involved +## Repositories Involved [Startup subsystem](../device-dev/subsystems/subsys-boot-overview.md) @@ -123,4 +87,4 @@ base/startup/ [startup_init_lite](https://gitee.com/openharmony/startup_init_lite) -[startup\_syspara\_lite](https://gitee.com/openharmony/startup_syspara_lite) +[startup\_syspara\_lite](https://gitee.com/openharmony/startup_syspara_lite) \ No newline at end of file diff --git a/en/release-notes/OpenHarmony-v1-1-4-LTS.md b/en/release-notes/OpenHarmony-v1-1-4-LTS.md index e964014d2bb0c29127a921eb4ce4ee556fd68142..1854f89a4084873937bb7540fbe5afe1484916b4 100644 --- a/en/release-notes/OpenHarmony-v1-1-4-LTS.md +++ b/en/release-notes/OpenHarmony-v1-1-4-LTS.md @@ -77,7 +77,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | -------- | -------- | | [I4AJEN](https://gitee.com/openharmony/third_party_freetype/issues/I4AJEN) | Fixed the CVE-2020-15999 security vulnerability of the third_party_freetype component.| | [I4AJ6T](https://gitee.com/openharmony/third_party_mbedtls/issues/I4AJ6T) | Fixed the CVE-2020-36475 and CVE-2020-36478 security vulnerabilities of the third_party_mbedtls component.| -| [I4AIYJ](https://gitee.com/openharmony/device_hisilicon_third_party_uboot/issues/I4AIYJ?from=project-issue) | Fixed the CVE-2021-27138 and CVE-2021-27097 security vulnerabilities of the third_party_uboot component.| +| I4AIYJ | Fixed the CVE-2021-27138 and CVE-2021-27097 security vulnerabilities of the third_party_uboot component.| | [I4HUM6](https://gitee.com/openharmony/third_party_lwip/issues/I4HUM6?from=project-issue) | Fixed the CVE-2020-22284 security vulnerability of the third_party_lwip component.| | I4QTVZ | Fixed the CVE-2021-44732 and CVE-2021-45450 security vulnerabilities of the third_party_mbedtls component.| | [I46RRM](https://gitee.com/openharmony/third_party_wpa_supplicant/issues/I46RRM?from=project-issue) | Fixed copying of secondary device types for the P2P group client.| diff --git a/en/release-notes/OpenHarmony-v3.0-LTS.md b/en/release-notes/OpenHarmony-v3.0-LTS.md index a7f029ed5010e3df2f07787e4dfe8b22666ab1b5..131148f4ad92d542b68d70cc2f84edf865383c02 100644 --- a/en/release-notes/OpenHarmony-v3.0-LTS.md +++ b/en/release-notes/OpenHarmony-v3.0-LTS.md @@ -179,6 +179,6 @@ Table 5 Issues resolved for the standard system | [I48IM7](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I48IM7) | During the hilog pressure test, **hilogd** restarts unexpectedly, and the **hilog** command cannot be used.| In the pressure test, there is a low probability that the log output is abnormal. The log output is normal in the commissioning scenario.| October 30| | I48YPH | [DSoftBus - Networking] During the testing of the getting-offline - discovery - networking cycle, there are 3 failures among all the 110 attempts.| There is a low probability that this issue occurs. If a networking failure occurs, initiate the networking again.| October 30| | [I4BVVW](https://gitee.com/openharmony/communication_dsoftbus/issues/I4BVVW) | [DSoftBus - Networking] The success rate of self-networking between a standard-system device and mobile phone is 97%.| There is a low probability that the networking fails.| October 30| -| [I4BXWY](https://gitee.com/openharmony/multimedia_media_standard/issues/I4BXWY) | For Hi3516, noises occur during playback of an audio recording.| This issue occurs only when this development board is used.| October 30| -| [I4BXY1](https://gitee.com/openharmony/multimedia_camera_standard/issues/I4BXY1) | There is no sound in the first few seconds of a video recording, the sound and image are out of sync, frame freezing occurs, and noises occur when the audio source was far away during recording.| This issue occurs only when this development board is used.| October 30| +| I4BXWY | For Hi3516, noises occur during playback of an audio recording.| This issue occurs only when this development board is used.| October 30| +| I4BXY1 | There is no sound in the first few seconds of a video recording, the sound and image are out of sync, frame freezing occurs, and noises occur when the audio source was far away during recording.| This issue occurs only when this development board is used.| October 30| | [3ZJ1D](https://gitee.com/openharmony/kernel_liteos_a/issues/I3ZJ1D) | There is a possibility that the user mode fails in the XTS pressure test of the permission case.| There is a low probability that the UID of a child process fails to be set in the XTS pressure test scenario where child processes are repeatedly created.| October 30| diff --git a/en/release-notes/OpenHarmony-v3.0.1-LTS.md b/en/release-notes/OpenHarmony-v3.0.1-LTS.md index 93c97e5a99e41cfd30bc037c52959b655999d205..afec9959428f2824189e6c83abadf3e8bc134310 100644 --- a/en/release-notes/OpenHarmony-v3.0.1-LTS.md +++ b/en/release-notes/OpenHarmony-v3.0.1-LTS.md @@ -83,27 +83,27 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4BJFU](https://gitee.com/openharmony/kernel_liteos_a/issues/I4BJFU) | An error occurs when the dyload_posix module removes a file.| | [I42N33](https://gitee.com/openharmony/third_party_mksh/issues/I42N33) | During the integration test, the Ctrl+C operation does not function after the **cat** command is run. A device restart is required.| | [I4C8BO](https://gitee.com/openharmony/docs/issues/I4C8BO?from=project-issue) | The basic functions of the media subsystem (on a mini- or small-system device) are abnormal when Hi3516D V300 or Hi3518E V300 is burnt and configured by following the instructions in the official website.| -| [I4BWKC](https://gitee.com/openharmony/drivers_framework/issues/I4BWKC) | The camera driver on the Hi3516D V300 board does not function properly in the pressure test.| -| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | The **ResetDriver** interface of the Hi3516D V300 board fails to be called.| +| I4BWKC | The camera driver on the Hi3516D V300 board does not function properly in the pressure test.| +| I4BW0G | The **ResetDriver** interface of the Hi3516D V300 board fails to be called.| | [I4C7ZK](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4C7ZK) | For Hi3516D V300, the resident memory of the small system exceeds the baseline.| | [I434P1](https://gitee.com/openharmony/multimedia_camera_lite/issues/I434P1) | For Hi3518E V300, the resident memory exceeds the baseline.| | [I48IM7](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I48IM7) | During the HiLog pressure test, the hilogd restarts unexpectedly, and the hilog commands cannot be used.| -| [I4EGMD](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4EGMD) | The serialization and deserialization methods of **Want** are defective.| +| I4EGMD | The serialization and deserialization methods of **Want** are defective.| | [I4CED3](https://gitee.com/openharmony/account_os_account/issues/I4CED3) | The JS API returns both "err" and "data" in one message.| -| [I4BXZ1](https://gitee.com/openharmony/app_samples/issues/I4BXZ1) | The **\** component does not respond to clicks.| -| [I4CMMH](https://gitee.com/openharmony/ace_ace_engine/issues/I4CMMH) | The display effect of the **\** component is abnormal.| -| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | The response time of the edit box is inappropriate.| +| I4BXZ1 | The **\** component does not respond to clicks.| +| I4CMMH | The display effect of the **\** component is abnormal.| +| I4CE7D | The response time of the edit box is inappropriate.| | [I4HI4C](https://gitee.com/openharmony/ai_engine/issues/I4HI4C) | There is a failed item of the TDD test on a small-system device. This failure is caused by the inappropriate test case comparison time range.| | [I4EUOW](https://gitee.com/openharmony/ai_engine/issues/I4EUOW) | The number of case execution threads is inappropriate.| -| [I4HTFS](https://gitee.com/openharmony/appexecfwk_appexecfwk_lite/issues/I4HTFS) | BMS adaptation for the mini system is not supported.| +| I4HTFS | BMS adaptation for the mini system is not supported.| | [I4C3BE](https://gitee.com/openharmony/communication_dsoftbus/issues/I4C3BE) | During passive Bluetooth Low Energy (BLE) discovery, the Bluetooth advertisement is frequently updated and, when the Bluetooth resources are used up, automatically disabled.| | [I4I7QL](https://gitee.com/openharmony/developtools_packing_tool/issues/I4I7QL) | Packing fails when an ability has two widgets.| -| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | There is a possibility that the Wi-Fi **ResetDriver** interface fails to be called.| +| I4BW0G | There is a possibility that the Wi-Fi **ResetDriver** interface fails to be called.| | [I4GBB6](https://gitee.com/openharmony/device_qemu/issues/I4GBB6) | The RISC-V QEMU emulator fails to run.| | [I4CE7E](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CE7E) | **drivers/mtd/multi_partition/** in the LiteOS-A kernel is implemented by using the driver functions in **device/hisilicon**.| -| [I4JBEH](https://gitee.com/openharmony/drivers_framework/issues/I4JBEH) | Memory leakage occurs when the DMA transmission interface of HDF is repeatedly used.| -| [I4IGQ0](https://gitee.com/openharmony/drivers_framework/issues/I4IGQ0) | Resources are released after component detection fails.| -| [I4JPCG](https://gitee.com/openharmony/drivers_framework/issues/I4JPCG) | The PWM backlight cannot be set to 0.| +| I4JBEH | Memory leakage occurs when the DMA transmission interface of HDF is repeatedly used.| +| I4IGQ0 | Resources are released after component detection fails.| +| I4JPCG | The PWM backlight cannot be set to 0.| | [I4ERM4](https://gitee.com/openharmony/drivers_peripheral/issues/I4ERM4) | A test case fails to be displayed.| | [I4CMUY](https://gitee.com/openharmony/drivers_adapter_khdf_linux/issues/I4CMUY) | The hdf\_peripheral\_wlan\_test\_performance.bin test suite fails to run.| | [I4FIP2](https://gitee.com/openharmony/kernel_liteos_a/issues/I4FIP2) | The **ioctl** function of the LiteOS_A kernel does not support the **SIOCGIFBRDADDR** option.| @@ -118,7 +118,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4C5RW](https://gitee.com/openharmony/kernel_liteos_m/issues/I4C5RW) | The error indicating that the **OS_TASK_STACK_PROTECT_SIZE** macro is not defined occurs when the MPU is enabled to protect the task stack.| | [I4G4VK](https://gitee.com/openharmony/kernel_liteos_m/issues/I4G4VK) | Some macros are inappropriate. If they (for example, **inet_addr**) are changed to functions, the lwIP header file is not required for external calling.| | [I4FVGV](https://gitee.com/openharmony/kernel_liteos_m/issues/I4FVGV) | The default lwIP configuration of the LiteOS_M kernel is inappropriate.| -| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | There is no necessary to start the input method after a 3-second delay.| +| I4CE7D | There is no necessary to start the input method after a 3-second delay.| | [I4CFOO](https://gitee.com/openharmony/multimedia_media_lite/issues/I4CFOO) | After an application running on the Linux system records videos for multiple times, the size of the last recording file is 0 when the system is restarted without exiting the application.| | [I4CLGW](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CLGW) | The page cache is inappropriate.| | [I4HKQ2](https://gitee.com/openharmony/vendor_hisilicon/issues/I4HKQ2) | The mechanism for the LiteOS running on a mini-system board to obtain the UDID is inappropriate.| @@ -132,24 +132,24 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4BX4J](https://gitee.com/openharmony/hiviewdfx_hicollie/issues/I4BX4J?from=project-issue) | The Hi3516D V300 board fails to call the **hicollie** interface.| | [I4BX1X](https://gitee.com/openharmony/hiviewdfx_hitrace/issues/I4BX1X?from=project-issue) | The Hi3516D V300 board fails to call the **hitrace** interface.| | [I4BVUL](https://gitee.com/openharmony/communication_wifi/issues/I4BVUL?from=project-issue) | When access points (APs) are changed, the success rate for networking between standard-system devices and mobile phones is 91%, lower than the expected value (98%).| -| [I4BW6E](https://gitee.com/openharmony/security_deviceauth/issues/I4BW6E) | During the test for networking between standard-system devices and mobile phones, when the mobile phone disables and enables the network access repeatedly for around 30 times, the networking fails.| +| I4BW6E | During the test for networking between standard-system devices and mobile phones, when the mobile phone disables and enables the network access repeatedly for around 30 times, the networking fails.| | [I4BVVW](https://gitee.com/openharmony/communication_dsoftbus/issues/I4BVVW) | During the test for networking between standard-system devices and mobile phones, when the Wi-Fi switch is turned on and off repeatedly, the networking success rate is 97%, lower than the expected value.| -| [I48YPH](https://gitee.com/openharmony/security_deviceauth/issues/I48YPH?from=project-issue) | During the test for discovery and networking performance, 3 out of 110 networking attempts fails.| +| I48YPH | During the test for discovery and networking performance, 3 out of 110 networking attempts fails.| | [I4492M](https://gitee.com/openharmony/communication_dsoftbus/issues/I4492M) | The offline device detection takes about 30s longer than the specifications.| -| [I44W7U](https://gitee.com/openharmony/graphic_standard/issues/I44W7U?from=project-issue) | The child window does not support zooming. As a result, the progress bar is hidden during video playback.| +| I44W7U | The child window does not support zooming. As a result, the progress bar is hidden during video playback.| | [I480Z1](https://gitee.com/openharmony/communication_dsoftbus/issues/I480Z1?from=project-issue) | Softbus_server crashes when executing **socketfuzz**.| -| [I4BGLS](https://gitee.com/openharmony/security_deviceauth/issues/I4BGLS?from=project-issue) | The key imported by using `import_signed_auth_info_hilink` is used for identifying the HiChain connection. After the key is imported, it is encrypted and stored in the file and is not cleared from the heap after being returned.| +| I4BGLS | The key imported by using `import_signed_auth_info_hilink` is used for identifying the HiChain connection. After the key is imported, it is encrypted and stored in the file and is not cleared from the heap after being returned.| | [I4A10Q](https://gitee.com/openharmony/startup_appspawn/issues/I4A10Q?from=project-issue) | The performance of Hi3516 3.0.0.6 static KPIs deteriorates severely.| -| [I4BXYT](https://gitee.com/openharmony/developtools_hdc_standard/issues/I4BXYT) | After device restart, developers must run the **hdc_std kill** command to discover the device again.| -| [I4KUTY](https://gitee.com/openharmony/ace_engine_lite/issues/I4KUTY) | There are invalid return values.| -| [I4DMFV](https://gitee.com/openharmony/ark_js_runtime/issues/I4DMFV) | The conversion from UTF-16 to UTF-8 is inappropriate.| +| I4BXYT | After device restart, developers must run the **hdc_std kill** command to discover the device again.| +| I4KUTY | There are invalid return values.| +| I4DMFV | The conversion from UTF-16 to UTF-8 is inappropriate.| | [I4HGVM](https://gitee.com/openharmony/communication_dsoftbus/issues/I4HGVM) | The dependency on mbedTLS is missing for the standard system.| -| [I4DLV2](https://gitee.com/openharmony/drivers_framework/issues/I4DLV2) | An invalid memory access error occurs due to the HidInfo\* type.| +| I4DLV2 | An invalid memory access error occurs due to the HidInfo\* type.| | [I4CIJJ](https://gitee.com/openharmony/third_party_flutter/issues/I4CIJJ) | ACE does not support GPU rendering.| | [I4G31Z](https://gitee.com/openharmony/third_party_freetype/issues/I4G31Z) | An update for the font engine version from 2.10.1 to 2.10.4 is unavailable.| | [I4H06M](https://gitee.com/openharmony/third_party_harfbuzz/issues/I4H06M) | An update for the OpenType text shaping engine from 2.6.1 to 2.8.1 is unavailable.| | [I4FS7V](https://gitee.com/openharmony/third_party_lwip/issues/I4FS7V) | The **LWIP\_NETCONN\_FULLDUPLEX** macro is not used to control the initialization of **conn->mbox\_threads\_waiting**.| -| [I43KL7](https://gitee.com/openharmony/graphic_standard/issues/I43KL7) | The synthesizer does not support GPU synthesis.| +| I43KL7 | The synthesizer does not support GPU synthesis.| ## Known Issues @@ -164,4 +164,4 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4OWWM](https://gitee.com/openharmony/xts_acts/issues/I4OWWM) | The JSON file corresponding to the WeekPluralNumbertest module is incorrectly configured. During case execution, the error message "required device does not exist" is displayed.| The JSON file configuration is incorrect. This issue does not affect functions.| 2022/01/15 | | [I4MSVV](https://gitee.com/openharmony/xts_acts/issues/I4MSVV?from=project-issue) | During the XTS test on the standard system, there are three failed items of the HiCollieCppTest cases in the ActsHiCollieCppTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | | [I4MSWM](https://gitee.com/openharmony/xts_acts/issues/I4MSWM?from=project-issue) | During the XTS test on the standard system, there is one failed item for faultloggertest in the ActsFaultLoggerTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | -| [I4NODO](https://gitee.com/openharmony/device_manager/issues/I4NODO) | During the test for the Hi3516 board running on a standard-system device, the E2E test of the distributed service hopping fails.| The DM component fails to repeatedly create a group. This issue affects the services that use hopping in the same way as that described in the issue details. Other services are not affected.| 2022/01/30 | +| I4NODO | During the test for the Hi3516 board running on a standard-system device, the E2E test of the distributed service hopping fails.| The DM component fails to repeatedly create a group. This issue affects the services that use hopping in the same way as that described in the issue details. Other services are not affected.| 2022/01/30 | diff --git a/en/release-notes/OpenHarmony-v3.0.2-LTS.md b/en/release-notes/OpenHarmony-v3.0.2-LTS.md index 2217b69fe43325f02905faad9b84eed14c27176e..640c459e9848f618a77e5f25de7527a168d1995e 100644 --- a/en/release-notes/OpenHarmony-v3.0.2-LTS.md +++ b/en/release-notes/OpenHarmony-v3.0.2-LTS.md @@ -85,7 +85,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4V2DN](https://gitee.com/openharmony/xts_acts/issues/I4V2DN?from=project-issue) | The execution of two test cases times out during the ActsLwipTest module test.| | [I4V3KC](https://gitee.com/openharmony/xts_acts/issues/I4V3KC?from=project-issue) | The test case testPublish0010 fails in the Distributed Scheduler.| | [I4URGA](https://gitee.com/openharmony/applications_sample_camera/issues/I4URGA?from=project-issue) | A blue screen may appear when users search for WLAN signals on the **Settings** page.| -| [I4SDCK](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4SDCK?from=project-issue) | An empty path or garbled characters are returned when users run **GetSrcPath** or **GetDataPath** on the Hi3516 development board of a small-system device.| +| I4SDCK | An empty path or garbled characters are returned when users run **GetSrcPath** or **GetDataPath** on the Hi3516 development board of a small-system device.| | [I4T6KZ](https://gitee.com/openharmony/communication_dsoftbus/issues/I4T6KZ) | The execution of **SendMessage** and **SendData4Data** fails during the transmission test.| | I4UOUS | Plaintext passwords are printed in the logs of the serial port interface on the Hi3516 development board of a small-system device.| | [I4OWZO](https://gitee.com/openharmony/third_party_toybox/issues/I4OWZO) | An error message is displayed when the **toybox mv** command is run to move a file in the NFS path.| @@ -97,7 +97,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4R4D3](https://gitee.com/openharmony/kernel_liteos_m/issues/I4R4D3) | The **detach** attribute is not set for the thread created by **pthread_create**. After the thread proactively exits and **OsGetAllTskInfo** is invoked, the related task name contains garbled characters.| | [I4R4A5](https://gitee.com/openharmony/kernel_liteos_m/issues/I4R4A5) | Compute overflow occurs in the implementation of the **pthread_cond_timedwait** interface.| | [I4QJT4](https://gitee.com/openharmony/drivers_adapter_khdf_linux/issues/I4QJT4) | The UartRead test case fails.| -| [I4U1DM](https://gitee.com/openharmony/distributedschedule_samgr_lite/issues/I4U1DM) | No lock is added when the LFQUE_Pop function is invoked by the QUEUE_Popfunction of samgr, causing potential data competition.| +| I4U1DM | No lock is added when the LFQUE_Pop function is invoked by the QUEUE_Popfunction of samgr, causing potential data competition.| **Table 4** Issues resolved for the standard system @@ -106,7 +106,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | [I4UJNU](https://gitee.com/openharmony/applications_settings/issues/I4UJNU) | The WLAN password is displayed in plaintext in the hilog when the WLAN is connected.| | [I4MSWM](https://gitee.com/openharmony/xts_acts/issues/I4MSWM?from=project-issue) | During the XT test, there is one failed item in the faultloggertest case of the ActsFaultLoggerTest module.| | [I4MSVV](https://gitee.com/openharmony/xts_acts/issues/I4MSVV?from=project-issue) | During the XTS test, there are three failed items in the HiCollieCppTest case of the ActsHiCollieCppTest module.| -| [I4PPXV](https://gitee.com/openharmony/appexecfwk_standard/issues/I4PPXV?from=project-issue) | The application icon is missing after a user opens an application, exits the application, and then returns to the home screen.| +| I4PPXV | The application icon is missing after a user opens an application, exits the application, and then returns to the home screen.| | [I4OF9A](https://gitee.com/openharmony/distributeddatamgr_file/issues/I4OF9A?from=project-issue) | The **text** value read by the **file.readText** interface is unstable.| | [I4OWWM](https://gitee.com/openharmony/xts_acts/issues/I4OWWM) | The JSON file corresponding to the WeekPluralNumbertest module is incorrectly configured. When a test case is executed, "required device does not exist" is reported, and the test suite cannot be executed.| | [I4OUVQ](https://gitee.com/openharmony/xts_tools/issues/I4OUVQ?from=project-issue) | During repeated pressure tests of XTS JS cases, the system stops responding and the test cannot continue.| diff --git a/en/release-notes/OpenHarmony-v3.0.3-LTS.md b/en/release-notes/OpenHarmony-v3.0.3-LTS.md index 4ac283b9a695bd2b1aa7ab67dc11e6954b887729..73a4b611aea81a586ccf37d0a3bd891732c54b1a 100644 --- a/en/release-notes/OpenHarmony-v3.0.3-LTS.md +++ b/en/release-notes/OpenHarmony-v3.0.3-LTS.md @@ -10,12 +10,12 @@ OpenHarmony 3.0.3 LTS is a maintenance version of OpenHarmony 3.0 LTS. This vers **Table 1** Version mapping of software and tools -| Software/Tool| Version| Remarks| +| Software/Tool| Version| Remarks| | -------- | -------- | -------- | -| OpenHarmony | 3.0.3 LTS | NA | -| SDK | 3.0.0.0(API Version 7 release) | NA | -| (Optional) HUAWEI DevEco Studio| 3.0 Beta1 | Recommended for developing OpenHarmony applications| -| (Optional) HUAWEI DevEco Device Tool| 2.2 Beta2 | Recommended for developing OpenHarmony smart devices| +| OpenHarmony | 3.0.3 LTS | NA | +| SDK | 3.0.0.0(API Version 7 release) | NA | +| (Optional) HUAWEI DevEco Studio| 3.0 Beta1 | Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| 2.2 Beta2 | Recommended for developing OpenHarmony smart devices| ## Source Code Acquisition @@ -25,7 +25,7 @@ OpenHarmony 3.0.3 LTS is a maintenance version of OpenHarmony 3.0 LTS. This vers **Method 1 (recommended)**: Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.) - + ``` repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.3-LTS --no-repo-verify repo sync -c @@ -34,7 +34,7 @@ repo forall -c 'git lfs pull' **Method 2**: Use the **repo** tool to download the source code over HTTPS. - + ``` repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.3-LTS --no-repo-verify repo sync -c @@ -46,13 +46,13 @@ repo forall -c 'git lfs pull' **Table 2** Mirrors for acquiring source code -| LTS Code| Version| Mirror| SHA-256 Checksum| +| LTS Code| Version| Mirror| SHA-256 Checksum| | -------- | -------- | -------- | -------- | -| Full code base (for mini, small, and standard systems)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/code-v3.0.3-LTS.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/code-v3.0.3-LTS.tar.gz.sha256)| -| Standard system Hi3516 solution (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/standard.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/standard.tar.gz.sha256) | -| Mini system Hi3861 solution (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_pegasus.tar.gz.sha256) | -| Small system Hi3516 solution - LiteOS (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus.tar.gz.sha256) | -| Small system Hi3516 solution - Linux (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus_linux.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus_linux.tar.gz.sha256) | +| Full code base (for mini, small, and standard systems)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/code-v3.0.3-LTS.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/code-v3.0.3-LTS.tar.gz.sha256)| +| Standard system Hi3516 solution (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/standard.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/standard.tar.gz.sha256) | +| Mini system Hi3861 solution (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_pegasus.tar.gz.sha256) | +| Small system Hi3516 solution - LiteOS (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus.tar.gz.sha256) | +| Small system Hi3516 solution - Linux (binary)| 3.0.3 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus_linux.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.3/hispark_taurus_linux.tar.gz.sha256) | ## What's New @@ -79,32 +79,32 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op **Table 3** Resolved issues -| Issue No.| Description| +| Issue No.| Description| | -------- | -------- | -| [I4TUSX](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4TUSX) | When the system camera is used to take a photo in the Hi3516D V300 development board running on a mini-system device, the two edges of the image are truncated.| -| [I4TYOP](https://gitee.com/openharmony/drivers_peripheral/issues/I4TYOP) | After a USB flash drive is inserted into the Hi3516D V300 development board running on a mini-system device, DMA times out and the USB flash drive is unavailable.| -| [I4SM0J](https://gitee.com/openharmony/third_party_harfbuzz/issues/I4SM0J) | The **third_party_harfbuzz** repository uses the CC BY-NC-SA-3.0 license, which restricts the commercial use of the content in the repository.| -| [I4WPQW](https://gitee.com/openharmony/device_hisilicon_hardware/issues/I4WPQW) | The **libdisplay_layer.so** binary file is not updated in the **device_hisilicon_hardware** repository.| -| [I4WIVF](https://gitee.com/openharmony/third_party_boost/issues/I4WIVF) | Some files in the **third_party_boost** repository are incompatible with open-source protocols.| -| [I4WRWM](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4WRWM) | Some TDD test cases are unavailable in the **aafwk_aafwk_lite** repository.| -| [I4VPVY](https://gitee.com/openharmony/applications_sample_camera/issues/I4VPVY) | In the Hi3516D V300 development board running on a mini-system device, a user searches for Wi-Fi in **Settings** and touches the back button twice to return to the home screen. No application can be started from the home screen.| -| [I4UTY0](https://gitee.com/openharmony/applications_photos/issues/I4UTY0) | The HP copyright statement exists in the metadata of the **1.jpg** file in **demos**.| -| [I4TP6D](https://gitee.com/openharmony/xts_acts/issues/I4TP6D) | The ActsWorkerJSTest test suite newly added for the Hi3516 development board running on a standard-system device cannot be executed properly.| +| [I4TUSX](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4TUSX) | When the system camera is used to take a photo in the Hi3516D V300 development board running on a mini-system device, the two edges of the image are truncated.| +| [I4TYOP](https://gitee.com/openharmony/drivers_peripheral/issues/I4TYOP) | After a USB flash drive is inserted into the Hi3516D V300 development board running on a mini-system device, DMA times out and the USB flash drive is unavailable.| +| [I4SM0J](https://gitee.com/openharmony/third_party_harfbuzz/issues/I4SM0J) | The **third_party_harfbuzz** repository uses the CC BY-NC-SA-3.0 license, which restricts the commercial use of the content in the repository.| +| [I4WPQW](https://gitee.com/openharmony/device_hisilicon_hardware/issues/I4WPQW) | The **libdisplay_layer.so** binary file is not updated in the **device_hisilicon_hardware** repository.| +| [I4WIVF](https://gitee.com/openharmony/third_party_boost/issues/I4WIVF) | Some files in the **third_party_boost** repository are incompatible with open-source protocols.| +| I4WRWM | Some TDD test cases are unavailable in the **aafwk_aafwk_lite** repository.| +| [I4VPVY](https://gitee.com/openharmony/applications_sample_camera/issues/I4VPVY) | In the Hi3516D V300 development board running on a mini-system device, a user searches for Wi-Fi in **Settings** and touches the back button twice to return to the home screen. No application can be started from the home screen.| +| [I4UTY0](https://gitee.com/openharmony/applications_photos/issues/I4UTY0) | The HP copyright statement exists in the metadata of the **1.jpg** file in **demos**.| +| [I4TP6D](https://gitee.com/openharmony/xts_acts/issues/I4TP6D) | The ActsWorkerJSTest test suite newly added for the Hi3516 development board running on a standard-system device cannot be executed properly.| **Table 4** Resolved security vulnerabilities -| Issue No.| Description| +| Issue No.| Description| | -------- | -------- | -| I4U8VB | CVE-2021-3520 security vulnerability of the third_party_lz4 component.| -| I4UX33 | CVE-2021-22569 and CVE-2021-22570 security vulnerabilities of the third_party_protobuf component.| -| I4VRR7 | CVE-2022-23308 security vulnerability of the third_party_libxml2 component.| +| I4U8VB | CVE-2021-3520 security vulnerability of the third_party_lz4 component.| +| I4UX33 | CVE-2021-22569 and CVE-2021-22570 security vulnerabilities of the third_party_protobuf component.| +| I4VRR7 | CVE-2022-23308 security vulnerability of the third_party_libxml2 component.| **Table 5** Known issues -| Issue No.| Description| Impact| To Be Resolved On| +| Issue No.| Description| Impact| To Be Resolved On| | -------- | -------- | -------- | -------- | -| [I4YBB0](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YBB0) | No image is generated and the recorded video cannot be played when the system camera is used to take a photo and record a video. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera recording does not function.| 2022/04/01 | -| [I4YB87](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YB87) | No image is generated when the system camera is used to take a photo. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera photographing does not function.| 2022/04/01 | -| [I4YAGS](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YAGS?from=project-issue) | A blue screen is displayed when the system camera is accessed. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera preview does not function.| 2022/04/01 | -| [I4WLBU](https://gitee.com/openharmony/developtools_hdc_standard/issues/I4WLBU?from=project-issue) | In the Hi3516D V300 development board running on a standard-system device, the device cannot be found after burning during the ACTS test, and the message "Device not founded or connected" is reported.| The HDC tool causes the ACTS test to report this error occasionally. The error does not affect the actual function.| 2022/04/10 | +| [I4YBB0](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YBB0) | No image is generated and the recorded video cannot be played when the system camera is used to take a photo and record a video. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera recording does not function.| 2022/04/01 | +| [I4YB87](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YB87) | No image is generated when the system camera is used to take a photo. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera photographing does not function.| 2022/04/01 | +| [I4YAGS](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4YAGS?from=project-issue) | A blue screen is displayed when the system camera is accessed. This issue occurs only for the Hi3516D V300 development board running on a small-system device (Linux).| Camera preview does not function.| 2022/04/01 | +| I4WLBU | In the Hi3516D V300 development board running on a standard-system device, the device cannot be found after burning during the ACTS test, and the message "Device not founded or connected" is reported.| The HDC tool causes the ACTS test to report this error occasionally. The error does not affect the actual function.| 2022/04/10 | diff --git a/en/release-notes/OpenHarmony-v3.1-beta.md b/en/release-notes/OpenHarmony-v3.1-beta.md index c88ab035f4fdc786c2d71c0760da58f33069c752..473ab75402e29ce5e78e90f793e14b4423ce19f8 100644 --- a/en/release-notes/OpenHarmony-v3.1-beta.md +++ b/en/release-notes/OpenHarmony-v3.1-beta.md @@ -198,9 +198,9 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Issue No.| Description| | -------- | -------- | | [I48IM7](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I48IM7) | During the hilog pressure test, **hilogd** restarts unexpectedly, and the **hilog** command cannot be used.| -| [I48YPH](https://gitee.com/openharmony/security_deviceauth/issues/I48YPH) | [DSoftBus - Networking] During the testing of the getting-offline - discovery - networking cycle, there are 3 failures among all the 110 attempts.| +| I48YPH | [DSoftBus - Networking] During the testing of the getting-offline - discovery - networking cycle, there are 3 failures among all the 110 attempts.| | [I4BVVW](https://gitee.com/openharmony/communication_dsoftbus/issues/I4BVVW) | [DSoftBus - Networking] The success rate of automatic networking between a standard-system device and mobile phone is 97%.| -| [I4BXY1](https://gitee.com/openharmony/multimedia_camera_standard/issues/I4BXY1) | There is no sound in the first few seconds of a video recording, the sound and image are out of sync, frame freezing occurs, and noises occur when the audio source was far away during recording.| +| I4BXY1 | There is no sound in the first few seconds of a video recording, the sound and image are out of sync, frame freezing occurs, and noises occur when the audio source was far away during recording.| | [3ZJ1D](https://gitee.com/openharmony/kernel_liteos_a/issues/I3ZJ1D) | There is a possibility that the user mode fails in the XTS pressure test of the permission case.| @@ -212,7 +212,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | -------- | -------- | -------- | -------- | | [I4NRS5](https://gitee.com/openharmony/kernel_linux_5.10/issues/I4NRS5) | [Kernel subsystem] A CVE vulnerability exists.| No patch has been released for the Linux kernel. The kernel will be updated after the patch is released in the community.| Depending on the patch release in the community| | [I4MGJM](https://gitee.com/openharmony/drivers_peripheral/issues/I4MGJM) | [HDF/Camera] The case fails when the RK3568 board runs the camera HDI tests.| The photographing and preview functions are normal. The recording function can be started but cannot be stopped.| 2021/12/31 | -| [I4OECR](https://gitee.com/openharmony/ark_js_runtime/issues/I4OECR) | An Ark stack exception occurs during XTS running (low probability).| There is a low probability that the Ark stack becomes abnormal during the XTS pressure test. This issue occurs only once in 48 hours. The exception stack is reported only in the log and does not affect the functions.| 2022/01/05| +| I4OECR | An Ark stack exception occurs during XTS running (low probability).| There is a low probability that the Ark stack becomes abnormal during the XTS pressure test. This issue occurs only once in 48 hours. The exception stack is reported only in the log and does not affect the functions.| 2022/01/05| | [I4OBTW](https://gitee.com/openharmony/ability_ability_runtime/issues/I4OBTW) | After all XTS cases are executed and the application is installed, aa start failures occur, affecting the OpenHarmony pipeline stability test.| During the XTS pressure test, when 100 application packages are installed in batches in a short period of time, 2 of them cannot be started. User experience is not affected.| 2022/01/05| -| [I4OLHF](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLHF?from=project-issue) | [Ark subsystem] The test process is abnormal due to the com.amsst.amsMissionSnapshotTest process.| This issue occurs occasionally during high-pressure tests.| 2022/01/05| -| [I4OLUK](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLUK) | [Ark subsystem] The process stack is abnormal due to the com.ohos.systemui process.| This issue occurs occasionally during high-pressure tests.| 2022/01/05| +| I4OLHF | [Ark subsystem] The test process is abnormal due to the com.amsst.amsMissionSnapshotTest process.| This issue occurs occasionally during high-pressure tests.| 2022/01/05| +| I4OLUK | [Ark subsystem] The process stack is abnormal due to the com.ohos.systemui process.| This issue occurs occasionally during high-pressure tests.| 2022/01/05| diff --git a/en/release-notes/OpenHarmony-v3.1-release.md b/en/release-notes/OpenHarmony-v3.1-release.md index ee5861232094f53fd0fec463250e4dffbe28963f..e2f37c76e6c3fd32e868fd0ad3a3d60152407dda 100644 --- a/en/release-notes/OpenHarmony-v3.1-release.md +++ b/en/release-notes/OpenHarmony-v3.1-release.md @@ -215,7 +215,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | ArkUI | [Drag](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag)| This sample shows the drag operation function.| eTS | | ArkUI | [Animation](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation)| This sample demonstrates the effect of the **AnimatorProperty** and **Explicit Animation**.| eTS | | Data management| [Querying the DDM Result Set](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery)| This sample shows how to create a query object to query data in a key-value (KV) store and obtain the result set in distributed data management (DDM).| eTS | -| Data management| [eTS RDB](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb)| This sample shows how to use a relational database (RDB) in eTS, including adding, deleting, modifying, and querying data.| eTS | +| Data management| [eTS RDB](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | This sample shows how to use a relational database (RDB) in eTS, including adding, deleting, modifying, and querying data.| eTS | | Common event and notification| [Reminder Agent](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock)| This sample shows how to use the reminder agent by simulating an alarm clock.| eTS | | Common event and notification| [Event notification](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter)| This sample shows the in-process event notification. After a user selects an offering and submits an order, the selected offering is displayed in the order list.| eTS | | Connectivity| [RPC](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC)| This sample shows the data exchange between the frontend and backend of a device. After the offering and quantity are selected at the frontend, the backend calculates the result and displays it at the frontend.| eTS | @@ -248,10 +248,10 @@ For more information, visit [Samples](https://gitee.com/openharmony/app_samples) | Issue No.| Description| | -------- | -------- | | [I4MGJM](https://gitee.com/openharmony/drivers_peripheral/issues/I4MGJM) | [HDF/Camera] The case fails when the RK3568 board runs the camera HDI tests.| -| [I4OECR](https://gitee.com/openharmony/ark_js_runtime/issues/I4OECR) | An Ark stack exception occurs during XTS running (low probability).| +| I4OECR | An Ark stack exception occurs during XTS running (low probability).| | [I4OBTW](https://gitee.com/openharmony/ability_ability_runtime/issues/I4OBTW) | After all XTS cases are executed and the application is installed, aa start failures occur, affecting the pipeline stability test.| -| [I4OLHF](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLHF?from=project-issue) | [ArkUI subsystem] The test process is abnormal due to the com.amsst.amsMissionSnapshotTest process.| -| [I4OLUK](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLUK) | [ArkUI subsystem] The process stack is abnormal due to the com.ohos.systemui process.| +| I4OLHF | [ArkUI subsystem] The test process is abnormal due to the com.amsst.amsMissionSnapshotTest process.| +| I4OLUK | [ArkUI subsystem] The process stack is abnormal due to the com.ohos.systemui process.| ## Known Issues diff --git a/en/release-notes/OpenHarmony-v3.1.1-release.md b/en/release-notes/OpenHarmony-v3.1.1-release.md index bcff1ffc13392f7b2e563b7e97e679a6e048bee7..4a6b551d2812fd34f8de9f41dd36c47d488246b1 100644 --- a/en/release-notes/OpenHarmony-v3.1.1-release.md +++ b/en/release-notes/OpenHarmony-v3.1.1-release.md @@ -148,11 +148,11 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op **Table 4** Resolved issues -| Issue No. | Description | +| Issue No. | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [I4UUFR](https://gitee.com/openharmony/third_party_e2fsprogs/issues/I4UUFR) | Local image compilation and build may fail for the Hi3516 development board. | -| [I4WDD3](https://gitee.com/openharmony/multimedia_camera_standard/issues/I4WDD3) | [RK3568] A recorded video cannot be viewed. | -| [I50EBB](https://gitee.com/openharmony/docs/issues/I50EBB) | [Hi3516 burning] Images of the Hi3516 development board on a standard-system device cannot be burnt by using DevEco Device Tool. | +| [I4UUFR](https://gitee.com/openharmony/third_party_e2fsprogs/issues/I4UUFR) | Local image compilation and build may fail for the Hi3516 development board. | +| I4WDD3 | [RK3568] A recorded video cannot be viewed. | +| [I50EBB](https://gitee.com/openharmony/docs/issues/I50EBB) | [Hi3516 burning] Images of the Hi3516 development board on a standard-system device cannot be burnt by using DevEco Device Tool. | ## Known Issues diff --git a/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index e5f4ee612cd8a2d4f78186d9e441b74544de0b9a..f1165d75889e59d8e66ab512eaecf3d4a0e7d612 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -58,6 +58,8 @@ onBundleAdded(bundleName: string): void **系统能力**:SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -82,6 +84,8 @@ onBundleRemoved(bundleName: string): void **系统能力**:SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md index 738f1d435cc9b122042735559b2232af370c21ab..89e43e02cbb2de776cca4c6fa1f43cce120eac67 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -11,7 +11,7 @@ GesturePath表示手势路径信息。 ## 导入模块 ```ts -import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePath from '@ohos.accessibility.GesturePath'; ``` ## GesturePath @@ -43,7 +43,7 @@ constructor(durationTime: number); **示例:** -```typescript +```ts let durationTime = 20; let gesturePath = new GesturePath(durationTime); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md index b5a2cd1a6c1315b6d20e1cafbde2440f14880849..d787f38222017e3e524d8d4712f81af7873d5d41 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -11,7 +11,7 @@ GesturePoint表示手势触摸点。 ## 导入模块 ```ts -import GesturePoint from "@ohos.accessibility.GesturePoint"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; ``` ## GesturePoint @@ -44,7 +44,7 @@ constructor(positionX: number, positionY: number); **示例:** -```typescript +```ts let positionX = 1; let positionY = 2; let gesturePoint = new GesturePoint(positionX, positionY); diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md index 8ef198195d24b4bb0e52a89d1363d92bdff394d7..4d7842e34181c20e99e296135c343b359a48d1e5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @@ -8,8 +8,8 @@ ## 导入模块 -```typescript -import config from "@ohos.accessibility.config"; +```ts +import config from '@ohos.accessibility.config'; ``` ## 属性 @@ -27,171 +27,243 @@ import config from "@ohos.accessibility.config"; | mouseKey | [Config](#config)\| 是 | 是 | 表示鼠标键功能启用状态。 | | mouseAutoClick | [Config](#config)\| 是 | 是 | 表示鼠标自动点击功能启用状态。取值 0~5000,单位为毫秒。 | | shortkey | [Config](#config)\| 是 | 是 | 表示辅助扩展快捷键功能启用状态。 | -| shortkeyTarget | [Config](#config)\| 是 | 是 | 表示辅助扩展快捷键的目标配置。取值为辅助应用的名称,格式为:"bundleName/abilityName"。 | +| shortkeyTarget | [Config](#config)\| 是 | 是 | 表示辅助扩展快捷键的目标配置。取值为辅助应用的名称,格式为:'bundleName/abilityName'。 | | captions | [Config](#config)\| 是 | 是 | 表示辅助字幕功能启用状态。 | -| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| 是 | 是 | 表示辅助字幕的配置。 | +| captionsStyle | [Config](#config)\<[CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| 是 | 是 | 表示辅助字幕的配置。 | ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; +enableAbility(name: string, capability: Array<accessibility.Capability>): Promise<void>; -启用辅助扩展。 +启用辅助扩展,使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | name | string | 是 | 辅助应用的名称,格式为:"bundleName/abilityName"。 | - | capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | 是 | 辅助应用的能力属性。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)>) | 是 | 辅助应用的能力属性。 | **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | Promise实例,用于返回方法执行结果。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **示例:** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve']) - .then(() => { - console.info('enable succeed'); - }).catch((error) => { - console.error('enable failed'); - }); +```ts +let name = 'com.ohos.example/axExtension'; +let capability = ['retrieve']; +try { + config.enableAbility(name, capability).then(() => { + console.info('enable ability succeed'); + }).catch((err) => { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; ``` ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; +enableAbility(name: string, capability: Array<accessibility.Capability>, callback: AsyncCallback<void>): void; -启用辅助扩展。 +启用辅助扩展,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | name | string | 是 | 辅助应用的名称,格式为:"bundleName/abilityName"。 | - | capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | 是 | 辅助应用的能力属性。 | - | callback | AsyncCallback<void> | 是 | 回调函数,返回方法执行结果。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | 是 | 辅助应用的能力属性。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **示例:** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { - if (err) { - console.error('enable failed'); - return; - } - console.info('enable succeed'); - }) - ``` +```ts +let name = 'com.ohos.example/axExtension'; +let capability = ['retrieve']; +try { + config.enableAbility(name, capability, (err, data) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('enable ability succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility disableAbility(name: string): Promise<void>; -关闭辅助扩展。 +关闭辅助扩展,使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | name | string | 是 | 辅助应用的名称,格式为:"bundleName/abilityName"。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | Promise实例,用于返回方法执行结果。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **示例:** - ```typescript - config.disableAbility("com.ohos.example/axExtension") - .then(() => { - console.info('disable succeed'); - }).catch((error) => { - console.error('disable failed'); - }); - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.enableAbility(name).then(() => { + console.info('disable ability succeed'); + }).catch((err) => { + console.error('failed to disable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to disable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility disableAbility(name: string, callback: AsyncCallback<void>): void; -关闭辅助扩展。 +关闭辅助扩展,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | name | string | 是 | 辅助应用的名称,格式为:"bundleName/abilityName"。 | - | callback | AsyncCallback<void> | 是 | 回调函数,返回方法执行结果。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **示例:** - ```typescript - config.disableAbility("com.ohos.example/axExtension", (err, data) => { - if (err) { - console.error('disable failed'); - return; - } - console.info('disable succeed'); - }) - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name, (err, data) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('disable succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` -## on('enableAbilityListsStateChanged') +## on('enabledAccessibilityExtensionListChange') -on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; +on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void>): void; -添加启用的辅助扩展的列表变化监听。 +添加启用的辅助扩展的列表变化监听,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 参数固定为enableAbilityListsStateChanged,监听启用的辅助扩展的列表变化。 | - | callback | Callback<void> | 是 | 回调函数,在启用的辅助扩展的列表变化时通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 参数固定为enabledAccessibilityExtensionListChange,监听启用的辅助扩展的列表变化。 | +| callback | Callback<void> | 是 | 回调函数,在启用的辅助扩展的列表变化时通过此函数进行通知。 | **示例:** - ```typescript - config.on('enableAbilityListsStateChanged',() => { - console.info('ax extension ability enable list changed'); - }); - ``` +```ts +try { + config.on('enabledAccessibilityExtensionListChange', () => { + console.info('subscribe enabled accessibility extension list change state success'); + }).catch((err) => { + console.error('failed to subscribe enabled accessibility extension list change state, because ' + + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to subscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` -## off('enableAbilityListsStateChanged') +## off('enabledAccessibilityExtensionListChange') -off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; +off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void>): void; -取消启用的辅助扩展的列表变化监听。 +取消启用的辅助扩展的列表变化监听,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 否 | 参数固定为enableAbilityListsStateChanged,监听启用的辅助扩展的列表变化。 | - | callback | Callback<void> | 否 | 要取消的监听回调函数。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 否 | 参数固定为enabledAccessibilityExtensionListChange,监听启用的辅助扩展的列表变化。 | +| callback | Callback<void> | 否 | 要取消的监听回调函数。 | **示例:** - ```typescript - config.off('enableAbilityListsStateChanged'); - ``` +```ts +try { + config.off('enabledAccessibilityExtensionListChange', () => { + console.info('unSubscribe enabled accessibility extension list change state success'); + }).catch((err) => { + console.error('failed to unSubscribe enabled accessibility extension list change state, because ' + + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to unSubscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` ## Config @@ -201,152 +273,178 @@ off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): vo set(value: T): Promise<void>; -设置属性。 +设置属性,使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | value | T | 是 | 设置的属性值。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | T | 是 | 设置的属性值。 | **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | Promise实例,用于返回方法执行结果。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** - ```typescript - config.highContrastText.set(true) - .then(() => { - console.info('highContrastText set succeed'); - }).catch((error) => { - console.error('highContrastText set failed'); - }); - ``` +```ts +let value = true; +try { + config.highContrastText.set(value).then(() => { + console.info('set highContrastText succeed'); + }).catch((err) => { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### set set(value: T, callback: AsyncCallback<void>): void; -设置属性。 +设置属性,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | value | T | 是 | 设置的属性值。 | - | callback | AsyncCallback<void> | 是 | 回调函数,返回方法执行结果。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | T | 是 | 设置的属性值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** - ```typescript - config.highContrastText.set(true, (err, data) => { - if (err) { - console.error('highContrastText set failed'); - return; - } - console.info('highContrastText set succeed'); - }) - ``` +```ts +let value = true; +try { + config.highContrastText.set(value, (err, data) => { + if (err) { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('set highContrastText succeed'); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### get get(): Promise<T>; -获取属性。 +获取属性,使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<T> | Promise实例,用于返回属性值。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<T> | Promise对象,返回对应属性值。 | **示例:** - ```typescript - config.highContrastText.get() - .then((value) => { - console.info('highContrastText get succeed'); - }).catch((error) => { - console.error('highContrastText get failed'); - }); - ``` +```ts +let value; +config.highContrastText.get().then((data) => { + value = data; + console.info('get highContrastText success'); +}).catch((err) => { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); +}); +``` ### get get(callback: AsyncCallback<T>): void; -获取属性。 +获取属性,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 回调函数,返回属性值。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | 是 | 回调函数,返回属性值。 | **示例:** - ```typescript - config.highContrastText.get((err, data) => { - if (err) { - console.error('highContrastText get failed'); - return; - } - console.info('highContrastText get succeed'); - }) - ``` +```ts +let value; +config.highContrastText.get((err, data) => { + if (err) { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); + return; + } + value = data; + console.info('get highContrastText success'); +}); +``` ### on on(callback: Callback<T>): void; -添加属性变化监听。 +添加属性变化监听,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | Callback<T> | 是 | 回调函数,在属性变化时通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | 是 | 回调函数,在属性变化时通过此函数进行通知。 | **示例:** - ```typescript - config.highContrastText.on(() => { - console.info('highContrastText changed'); - }); - ``` +```ts +try { + config.highContrastText.on((err, data) => { + if (err) { + console.error('failed subscribe highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('subscribe highContrastText success'); + }); +} catch (exception) { + console.error('failed subscribe highContrastText, because ' + JSON.stringify(exception)); +} +``` ### off off(callback?: Callback<T>): void; -取消属性变化监听。 +取消属性变化监听,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | Callback<T> | 否 | 要取消的监听回调函数。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | 否 | 要取消的监听回调函数。 | **示例:** - ```typescript - config.highContrastText.off(); - ``` +```ts +config.highContrastText.off((err, data) => { + if (err) { + console.error('failed unSubscribe highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('unSubscribe highContrastText success'); +}); +``` ## DaltonizationColorFilter diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md index b82d3dfc5a8937c8c5af571e5c8088dc89415b2f..83dbfdf4b04c02670d2e5e5f3bfe12472288dd2f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -11,14 +11,15 @@ AccessibilityExtensionContext是AccessibilityExtensionAbility上下文环境, ## 使用说明 -在使用AccessibilityExtensionContext的功能前,需要通过AccessibilityExtensionAbility子类实例获取。 +在使用AccessibilityExtensionContext的功能前,需要通过AccessibilityExtensionAbility子类实例获取AccessibilityExtensionContex的实例。 ```js import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +let axContext; class MainAbility extends AccessibilityExtensionAbility { onConnect(): void { console.log('AxExtensionAbility onConnect'); - let axContext = this.context; + axContext = this.context; } } ``` @@ -97,11 +98,15 @@ setTargetBundleName(targetNames: Array\): Promise\; ```ts let targetNames = ['com.ohos.xyz']; -this.context.setTargetBundleName().then(() => { - console.info('set target bundle names success'); -}).catch((err) => { - console.error('failed to set target bundle names because ' + JSON.stringify(err)); -}); +try { + axContext.setTargetBundleName(targetNames).then(() => { + console.info('set target bundle names success'); + }).catch((err) => { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; ``` ## AccessibilityExtensionContext.setTargetBundleName @@ -123,13 +128,17 @@ setTargetBundleName(targetNames: Array\, callback: AsyncCallback\) ```ts let targetNames = ['com.ohos.xyz']; -this.context.setTargetBundleName().then((err, data) => { - if (err) { - console.error('failed to set target bundle names because ' + JSON.stringify(err)); - return; - } - console.info('set target bundle names success'); -}); +try { + axContext.setTargetBundleName(targetNames, (err, data) => { + if (err) { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + return; + } + console.info('set target bundle names success'); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; ``` ## AccessibilityExtensionContext.getFocusElement @@ -152,16 +161,28 @@ getFocusElement(isAccessibilityFocus?: boolean): Promise\; | ----------------------------------- | ---------------------- | | Promise<AccessibilityElement> | Promise对象,返回当前对应的焦点元素。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts let focusElement; -this.context.getFocusElement().then((data) => { - focusElement = data; - console.log('get focus element success'); -}).catch((err) => { - console.error('failed to get focus element because ' + JSON.stringify(err)); -}); +try { + axContext.getFocusElement().then((data) => { + focusElement = data; + console.log('get focus element success'); + }).catch((err) => { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getFocusElement @@ -178,18 +199,29 @@ getFocusElement(callback: AsyncCallback\): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回当前对应的焦点元素。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts -let focusElement; -this.context.getFocusElement().then((err, data) => { - if (err) { - console.error('failed to get focus element because ' + JSON.stringify(err)); - return; - } - focusElement = data; - console.info('get focus element success'); -}); +try { + axContext.getFocusElement((err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getFocusElement @@ -210,15 +242,18 @@ getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\ { +try { + axContext.getFocusElement(isAccessibilityFocus, (err, data) => { if (err) { - console.error('failed to get focus element because ' + JSON.stringify(err)); + console.error('failed to get focus element, because ' + JSON.stringify(err)); return; } focusElement = data; console.info('get focus element success'); }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindowRootElement @@ -240,16 +275,28 @@ getWindowRootElement(windowId?: number): Promise\; | ----------------------------------- | ---------------------- | | Promise<AccessibilityElement> | Promise对象,返回指定屏幕的所有窗口。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts let rootElement; -this.context.getWindowRootElement().then((data) => { - rootElement = data; - console.log('get root element of the window success'); -}).catch((err) => { - console.error('failed to get root element of the window because ' + JSON.stringify(err)); -}); +try { + axContext.getWindowRootElement().then((data) => { + rootElement = data; + console.log('get root element of the window success'); + }).catch((err) => { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get root element of the window, ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindowRootElement @@ -266,18 +313,29 @@ getWindowRootElement(callback: AsyncCallback\): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回指定窗口的根节点元素。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts -let rootElement; -this.context.getWindowRootElement().then((err, data) => { +try { + axContext.getWindowRootElement((err, data) => { if (err) { - console.error('failed to get root element of the window because ' + JSON.stringify(err)); + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); return; } rootElement = data; console.info('get root element of the window success'); }); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindowRootElement @@ -295,19 +353,29 @@ getWindowRootElement(windowId: number, callback: AsyncCallback\ { +try { + axContext.getWindowRootElement(windowId, (err, data) => { if (err) { - console.error('failed to get root element of the window because ' + JSON.stringify(err)); + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); return; } rootElement = data; console.info('get root element of the window success'); }); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindows @@ -330,16 +398,28 @@ getWindows(displayId?: number): Promise\>; | ----------------------------------- | ---------------------- | | Promise<Array<AccessibilityElement>> | Promise对象,返回指定屏幕的所有窗口。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts let windows; -this.context.getWindows().then((data) => { - windows = data; - console.log('get windows success'); -}).catch((err) => { - console.error('failed to get windows because ' + JSON.stringify(err)); -}); +try { + axContext.getWindows().then((data) => { + windows = data; + console.log('get windows success'); + }).catch((err) => { + console.error('failed to get windows, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindows @@ -356,18 +436,30 @@ getWindows(callback: AsyncCallback\>): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<AccessibilityElement>> | 是 | 回调函数,返回指定屏幕的所有窗口。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts let windows; -this.context.getWindows().then((err, data) => { - if (err) { - console.error('failed to get windows because ' + JSON.stringify(err)); - return; - } - windows = data; - console.info('get windows success'); -}); +try { + axContext.getWindows((err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.getWindows @@ -385,19 +477,31 @@ getWindows(displayId: number, callback: AsyncCallback\ { - if (err) { - console.error('failed to get windows because ' + JSON.stringify(err)); - return; - } - windows = data; - console.info('get windows success'); -}); +let displayId = 10; +try { + axContext.getWindows(displayId, (err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} ``` ## AccessibilityExtensionContext.injectGesture @@ -420,20 +524,32 @@ injectGesture(gesturePath: GesturePath): Promise\; | ----------------------------------- | ---------------------- | | Promise<void> | 无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts -import { GesturePath } from "../@ohos.accessibility.GesturePath"; +import GesturePath from "@ohos.accessibility.GesturePath"; let gesturePath = new GesturePath(100); -for (let i = 0; i < 10; i++) { - let gesturePoint = new GesturePosition(100, i * 200); - gesturePath.positions.push(gesturePoint); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath).then(() => { + console.info('inject gesture success'); + }).catch((err) => { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); } -this.context.gestureInject(gesturePath, () => { - console.info('inject gesture success'); -}).catch((err) => { - console.error('failed to inject gesture because ' + JSON.stringify(err)); -}); ``` ## AccessibilityExtensionContext.injectGesture @@ -450,25 +566,38 @@ injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void | gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | 是 | 表示手势的路径信息。 | | callback | AsyncCallback<void> | 是 | 回调函数,表示注入手势执行结果的回调。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + **示例:** ```ts +import GesturePath from "@ohos.accessibility.GesturePath"; let gesturePath = new GesturePath(100); -for (let i = 0; i < 10; i++) { - let gesturePoint = new GesturePosition(100, i * 200); - gesturePath.positions.push(gesturePoint); -} -this.context.gestureInject(gesturePath, (err, data) => { - if (err) { - console.error('failed to inject gesture because ' + JSON.stringify(err)); - return; +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); } - console.info('inject gesture success'); -}); + axContext.injectGesture(gesturePath, (err, data) => { + if (err) { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + return; + } + console.info('inject gesture success'); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} ``` -## AccessibilityElement9 +## AccessibilityElement9+ -无障碍节点元素。 +无障碍节点元素, 在调用AccessibilityElement的方法前,需要先通过[AccessibilityExtensionContext.getFocusElement()](#accessibilityextensioncontextgetfocuselement)或者[AccessibilityExtensionContext.getWindowRootElement()](#accessibilityextensioncontextgetwindowrootelement)获取AccessibilityElement实例。 **系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Core @@ -489,18 +618,14 @@ attributeNames\(): Promise\>; **示例:** ```ts -let accessibilityElement; +let rootElement; let attributeNames; -try { - accessibilityElement.attributeNames().then((data) => { - console.log('get attribute names success'); - attributeNames = data; - }).catch((err) => { - console.log('get attribute names err: ' + JSON.stringify(err)); - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} +rootElement.attributeNames().then((data) => { + console.log('get attribute names success'); + attributeNames = data; +}).catch((err) => { + console.log('failed to get attribute names, because ' + JSON.stringify(err)); +}); ``` ## attributeNames @@ -519,20 +644,16 @@ attributeNames\(callback: AsyncCallback\ **示例:** ```ts -let accessibilityElement; +let rootElement; let attributeNames; -try { - accessibilityElement.attributeNames().then((err, data) => { - if (err) { - console.error('failed to get attribute names because ' + JSON.stringify(err)); - return; - } - attributeNames = data; - console.info('get attribute names success'); - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} +rootElement.attributeNames((err, data) => { + if (err) { + console.error('failed to get attribute names, because ' + JSON.stringify(err)); + return; + } + attributeNames = data; + console.info('get attribute names success'); +}); ``` ## AccessibilityElement.attributeValue @@ -554,21 +675,27 @@ attributeValue\(attributeName: T): Promi | ---------------------------------------- | ------------------------ | | Promise<ElementAttributeValues[T]> | Promise对象,返回根据节点属性名称获取的属性值。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + **示例:** ```ts -let accessibilityElement; -let attributeValue; +let attributeName = 'name'; try { - let attributeName = 'name'; - accessibilityElement.attributeValue(attributeName).then((data) => { + rootElement.attributeValue(attributeName).then((data) => { console.log('get attribute value by name success'); attribtueValue = data; }).catch((err) => { - console.log('get attribute value by name err: ' + JSON.stringify(err)); + console.log('failed to get attribute value, because ' + JSON.stringify(err)); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); } ``` ## AccessibilityElement.attributeValue @@ -587,23 +714,31 @@ attributeValue\(attributeName: T, | attributeName | T | 是 | 表示属性的名称。 | | callback | AsyncCallback<ElementAttributeValues[T]> | 是 | 回调函数,返回根据节点属性名称获取的属性值。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + **示例:** ```ts -let accessibilityElement; +let rootElement; let attributeValue; +let attributeName = 'name'; try { - let attributeName = 'name'; - accessibilityElement.attributeValue(attributeName).then((err, data) => { + rootElement.attributeValue(attributeName, (err, data) => { if (err) { - console.error('failed to get attribute value because ' + JSON.stringify(err)); + console.error('failed to get attribute value, because ' + JSON.stringify(err)); return; } attributeValue = data; console.info('get attribute value success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); } ``` ## actionNames @@ -623,18 +758,14 @@ actionNames(): Promise\>; **示例:** ```ts -let accessibilityElement; +let rootElement; let actionNames; -try { - accessibilityElement.actionNames().then((data) => { - console.log('get action names success'); - actionNames = data; - }).catch((err) => { - console.log('get action names err: ' + JSON.stringify(err)); - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} +rootElement.actionNames().then((data) => { + console.log('get action names success'); + actionNames = data; +}).catch((err) => { + console.log('failed to get action names because ' + JSON.stringify(err)); +}); ``` ## actionNames @@ -653,20 +784,16 @@ actionNames(callback: AsyncCallback\>): void; **示例:** ```ts -let accessibilityElement; +let rootElement; let actionNames; -try { - accessibilityElement.actionNames().then((err, data) => { - if (err) { - console.error('failed to get action names because ' + JSON.stringify(err)); - return; - } - actionNames = data; - console.info('get action names success'); - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} +rootElement.actionNames((err, data) => { + if (err) { + console.error('failed to get action names, because ' + JSON.stringify(err)); + return; + } + actionNames = data; + console.info('get action names success'); +}); ``` ## performAction @@ -689,20 +816,28 @@ performAction(actionName: string, parameters?: object): Promise\; | ---------------------------------------- | ------------------------ | | Promise<boolean> | Promise对象,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。 | +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + **示例:** ```ts -let accessibilityElement; +let rootElement; let performActionRes; try { - accessibilityElement.performAction('action').then((data) => { + rootElement.performAction('action').then((data) => { console.info('perform action success'); performActionRes = data; }).catch((err) => { - console.log('failed to perform action because ' + JSON.stringify(err)); + console.log('failed to perform action, because ' + JSON.stringify(err)); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); } ``` ## performAction @@ -718,24 +853,32 @@ performAction(actionName: string, callback: AsyncCallback\): void; | 参数名 | 参数类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | actionName | string | 是 | 表示属性的名称。 | -| callback | AsyncCallback<boolean> | 是 | 回调函数,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。| + +**错误码:** + +以下错误码的详细介绍请参见[无障碍子系统错误码](../errorcodes/errorcode-accessibility.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | **示例:** ```ts -let accessibilityElement; +let rootElement; let performActionRes; try { - accessibilityElement.performAction('action').then((err, data) => { + rootElement.performAction('action', (err, data) => { if (err) { - console.error('failed to perform action because ' + JSON.stringify(err)); + console.error('failed to perform action, because ' + JSON.stringify(err)); return; } performActionRes = data; console.info('perform action success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); } ``` ## performAction @@ -752,35 +895,43 @@ performAction(actionName: string, parameters: object, callback: AsyncCallback\ { + rootElement.performAction(actionName, parameters, (err, data) => { if (err) { - console.error('failed to perform action because ' + JSON.stringify(err)); + console.error('failed to perform action, because ' + JSON.stringify(err)); return; } performActionRes = data; console.info('perform action success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); } ``` ## findElement('content') findElement(type: 'content', condition: string): Promise\>; -根据节点内容查询所有节点元素。 +根据节点内容查询所有节点元素,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -800,19 +951,19 @@ findElement(type: 'content', condition: string): Promise\ { + rootElement.findElement(type, condition).then((data) => { elements = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element because ' + JSON.stringify(err)); + console.log('failed to find element, because ' + JSON.stringify(err)); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` ## findElement('content') @@ -834,28 +985,28 @@ findElement(type: 'content', condition: string, callback: AsyncCallback\ { + rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element because ' + JSON.stringify(err)); + console.error('failed to find element, because ' + JSON.stringify(err)); return; } elements = data; console.info('find element success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` ## findElement('focusType') findElement(type: 'focusType', condition: FocusType): Promise\; -根据焦点元素类型查询节点元素。 +根据焦点元素类型查询节点元素,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -875,26 +1026,26 @@ findElement(type: 'focusType', condition: FocusType): Promise\ { - elements = data; + rootElement.findElement(type, condition).then((data) => { + element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element because ' + JSON.stringify(err)); + console.log('failed to find element, because ' + JSON.stringify(err)); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` ## findElement('focusType') findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; -根据焦点元素类型查询节点元素。 +根据焦点元素类型查询节点元素,使用callback异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -909,28 +1060,28 @@ findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\ { + rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element because ' + JSON.stringify(err)); + console.error('failed to find element, because ' + JSON.stringify(err)); return; } - elements = data; + element = data; console.info('find element success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` ## findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection): Promise\; -根据下一焦点元素方向查询节点元素。 +根据下一焦点元素方向查询节点元素,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -950,26 +1101,26 @@ findElement(type: 'focusDirection', condition: FocusDirection): Promise\ { - elements = data; + rootElement.findElement(type, condition).then((data) => { + element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element because ' + JSON.stringify(err)); + console.log('failed to find element, because ' + JSON.stringify(err)); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` ## findElement('focusDirection') findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; -根据下一焦点元素方向查询所有节点元素。 +根据下一焦点元素方向查询所有节点元素,使用callback异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -984,20 +1135,20 @@ findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCa **示例:** ```ts -let accessibilityElement; +let rootElement; let type = 'focusDirection'; let condition = 'up'; let elements; try { - accessibilityElement.findElement(type, condition).then((err, data) => { + rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element because ' + JSON.stringify(err)); + console.error('failed to find element, because ' + JSON.stringify(err)); return; } elements = data; console.info('find element success'); }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md index 77311ac0c1b9cc3f9c26db1b916ef21dc3d1f10f..b36394fe89ced28ce55eb7b16a5e8a74899a1df7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md @@ -7,7 +7,7 @@ ## 导入模块 -```typescript +```ts import accessibility from '@ohos.accessibility'; ``` @@ -144,7 +144,7 @@ import accessibility from '@ohos.accessibility'; ## CaptionsManager8+ -字幕配置管理,在调用CaptionsManager的方法前,需要先通过 [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8)获取 captionsManager实例。 +字幕配置管理,在调用CaptionsManager的方法前,需要先通过 [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8)获取 CaptionsManager实例。 **系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Hearing @@ -159,7 +159,7 @@ import accessibility from '@ohos.accessibility'; on(type: 'enableChange', callback: Callback<boolean>): void; -监听字幕配置启用状态变化事件。 +监听字幕配置启用状态变化事件,使用callback异步回调。 **参数:** @@ -170,18 +170,28 @@ on(type: 'enableChange', callback: Callback<boolean>): void; **示例:** - ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.on('enableChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }); - ``` +```ts +let result = false; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('enableChange', (err, data) => { + if (err) { + console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(err)); + return; + } + result = data; + console.info('subscribe caption manager enable state change success'); + }); +} catch (exception) { + console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### on('styleChange') on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -监听字幕风格变化事件。 +监听字幕风格变化事件,使用callback异步回调。 **参数:** @@ -192,18 +202,28 @@ on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; **示例:** - ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.on('styleChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }); - ``` +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('styleChange', (err, data) => { + if (err) { + console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(err)); + return; + } + captionStyle = data; + console.info('subscribe caption manager style state change success'); + }); +} catch (exception) { + console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` ### off('enableChange') off(type: 'enableChange', callback?: Callback<boolean>): void; -取消监听字幕配置启用状态变化事件。 +取消监听字幕配置启用状态变化事件,使用callback异步回调。 **参数:** @@ -214,18 +234,28 @@ off(type: 'enableChange', callback?: Callback<boolean>): void; **示例:** - ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.off('enableChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }); - ``` +```ts +let result = false; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('enableChange', (err, data) => { + if (err) { + console.error('failed to unSubscribe caption manager enable state change, because ' + JSON.stringify(err)); + return; + } + result = data; + console.info('unSubscribe caption manager enable state change success'); + }); +} catch (exception) { + console.error('failed to unSubscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### off('styleChange') off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -取消字幕风格变化监听事件。 +取消字幕风格变化监听事件,使用callback异步回调。 **参数:** @@ -236,12 +266,22 @@ off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; **示例:** - ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.off('styleChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }); - ``` +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('styleChange', (err, data) => { + if (err) { + console.error('failed to unSubscribe caption manager style state change, because ' + JSON.stringify(err)); + return; + } + captionStyle = data; + console.info('unSubscribe caption manager style state change success'); + }); +} catch (exception) { + console.error('failed to unSubscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` ## EventInfo @@ -284,11 +324,11 @@ constructor(jsonObject) **示例:** - ```typescript + ```ts let eventInfo = new accessibility.EventInfo({ - "type":"click", - "bundleName":"com.example.MyApplication", - "triggerAction":"click" + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' }); ``` @@ -340,12 +380,17 @@ constructor(jsonObject) | active | 窗口变为活动或不活动的窗口变化事件。 | | focus | 窗口焦点发生变化的窗口变化事件。 | -## accessibility.getAbilityLists +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> 查询辅助应用列表,使用Promise异步回调。 +> **说明:** +> +> 从API version 7开始支持,从API version 9开始废弃。 +> 推荐使用[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9)。 + **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** @@ -363,26 +408,39 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A **示例:** -```typescript -accessibility.getAbilityLists("spoken", "enable").then((data) => { - console.info('success data:getAbilityList1 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.bundleName); - } -}).catch((err) => { - console.error('failed to getAbilityList1 because ' + JSON.stringify(err)); -}); +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} ``` -## accessibility.getAbilityLists +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void 查询辅助应用列表,使用callback异步回调。 +> **说明:** +> +> 从API version 7开始支持,从API version 9开始废弃。 +> 推荐使用[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9-1)。 + **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** @@ -395,21 +453,120 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn **示例:** -```typescript -accessibility.getAbilityLists("visual", "enable", (err, data) => { - if (err) { - console.error('failed to getAbilityList2 because ' + JSON.stringify(err)); - return; - } - console.info('success data:getAbilityList2 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.bundleName); - } -}); - ``` +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + abilityList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> + +查询辅助应用列表,使用Promise异步回调。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | +| stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise对象,返回辅助应用信息列表。 | + +**示例:** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let extensionList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void + +查询辅助应用列表,使用callback异步回调。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | +| stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | 是 | 回调函数,返回辅助应用信息列表。 | + +**示例:** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let extensionList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` ## accessibility.getCaptionsManager8+ @@ -427,7 +584,7 @@ getCaptionsManager(): CaptionsManager **示例:** -```typescript +```ts let captionsManager = accessibility.getCaptionsManager(); ``` @@ -435,7 +592,7 @@ let captionsManager = accessibility.getCaptionsManager(); on(type: 'accessibilityStateChange', callback: Callback<boolean>): void -监听辅助应用启用状态变化事件。 +监听辅助应用启用状态变化事件,使用callback异步回调。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 @@ -448,17 +605,25 @@ on(type: 'accessibilityStateChange', callback: Callback<boolean>): void **示例:** -```typescript -accessibility.on('accessibilityStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) -}); +```ts +try { + accessibility.on('accessibilityStateChange', (err, data) => { + if (err) { + console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(err)); + return; + } + console.info('subscribe accessibility state change success'); + }); +} catch (exception) { + console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(exception)); +} ``` ## accessibility.on('touchGuideStateChange') on(type: 'touchGuideStateChange', callback: Callback<boolean>): void -监听触摸浏览功能启用状态变化事件。 +监听触摸浏览功能启用状态变化事件,使用callback异步回调。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 @@ -471,17 +636,25 @@ on(type: 'touchGuideStateChange', callback: Callback<boolean>): void **示例:** -```typescript -accessibility.on('touchGuideStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) -}); +```ts +try { + accessibility.on('touchGuideStateChange', (err, data) => { + if (err) { + console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(err)); + return; + } + console.info('subscribe touch guide state change success'); + }); +} catch (exception) { + console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(exception)); +} ``` ## accessibility.off('accessibilityStateChange') off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void -取消监听辅助应用启用状态变化事件。 +取消监听辅助应用启用状态变化事件,使用callback异步回调。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 @@ -494,17 +667,25 @@ off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void **示例:** -```typescript -accessibility.off('accessibilityStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) -}); +```ts +try { + accessibility.on('accessibilityStateChange', (err, data) => { + if (err) { + console.error('failed to unSubscribe accessibility state change, because ' + JSON.stringify(err)); + return; + } + console.info('unSubscribe accessibility state change success'); + }); +} catch (exception) { + console.error('failed to unSubscribe accessibility state change, because ' + JSON.stringify(exception)); +} ``` ## accessibility.off('touchGuideStateChange') off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void -取消监听触摸浏览启用状态变化事件。 +取消监听触摸浏览启用状态变化事件,使用callback异步回调。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 @@ -517,10 +698,18 @@ off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void **示例:** -```typescript -accessibility.off('touchGuideStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) -}); +```ts +try { + accessibility.on('touchGuideStateChange', (err, data) => { + if (err) { + console.error('failed to unSubscribe touch guide state change, because ' + JSON.stringify(err)); + return; + } + console.info('unSubscribe touch guide state change success'); + }); +} catch (exception) { + console.error('failed to unSubscribe touch guide state change, because ' + JSON.stringify(exception)); +} ``` ## accessibility.isOpenAccessibility @@ -539,7 +728,7 @@ isOpenAccessibility(): Promise<boolean> **示例:** -```typescript +```ts accessibility.isOpenAccessibility().then((data) => { console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) }).catch((err) => { @@ -563,7 +752,7 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void **示例:** -```typescript +```ts accessibility.isOpenAccessibility((err, data) => { if (err) { console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); @@ -589,7 +778,7 @@ isOpenTouchGuide(): Promise<boolean> **示例:** -```typescript +```ts accessibility.isOpenTouchGuide().then((data) => { console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) }).catch((err) => { @@ -613,7 +802,7 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void **示例:** -```typescript +```ts accessibility.isOpenTouchGuide((err, data) => { if (err) { console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); @@ -623,12 +812,17 @@ accessibility.isOpenTouchGuide((err, data) => { }); ``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo): Promise<void> 发送无障碍事件, 使用Promise异步回调。 +> **说明:** +> +> 从API version 7开始支持,从API version 9开始废弃。 +> 推荐使用[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9)。 + **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** @@ -645,11 +839,11 @@ sendEvent(event: EventInfo): Promise<void> **示例:** -```typescript +```ts let eventInfo = new accessibility.EventInfo({ - "type":"click", - "bundleName":"com.example.MyApplication", - "triggerAction":"click" + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' }); accessibility.sendEvent(eventInfo).then(() => { console.info('send event success'); @@ -658,12 +852,17 @@ accessibility.sendEvent(eventInfo).then(() => { }); ``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo, callback: AsyncCallback<void>): void 发送无障碍事件, 使用callback异步回调。 +> **说明:** +> +> 从API version 7开始支持,从API version 9开始废弃。 +> 推荐使用[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9-1)。 + **系统能力**:SystemCapability.BarrierFree.Accessibility.Core **参数:** @@ -675,11 +874,11 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void **示例:** -```typescript +```ts let eventInfo = new accessibility.EventInfo({ - "type":"click", - "bundleName":"com.example.MyApplication", - "triggerAction":"click" + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' }); accessibility.sendEvent(eventInfo, (err, data) => { if (err) { @@ -688,4 +887,79 @@ accessibility.sendEvent(eventInfo, (err, data) => { } console.info('sendEvent success'); }); - ``` +``` + +## accessibility.sendAccessibilityEvent9+ + +sendAccessibilityEvent(event: EventInfo): Promise<void> + +发送无障碍事件, 使用Promise异步回调。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | 是 | 无障碍事件对象。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendAccessibilityEvent(eventInfo).then(() => { + console.info('send event success'); + }).catch((err) => { + console.error('failed to send event because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` + +## accessibility.sendAccessibilityEvent9+ + +sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): void + +发送无障碍事件, 使用callback异步回调。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | 是 | 辅助事件对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,如果发送无障碍事件失败,则 AsyncCallback中err有数据返回。 | + +**示例:** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to send event because ' + JSON.stringify(err)); + return; + } + console.info('send event success'); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md index ea67b7e858460f02207609e1b16c42d33475b878..46efda388721bc8abf142aa6d021475cf3964dc9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @@ -94,8 +94,10 @@ onConnect(): void; **示例:** ```ts -onConnect(): void { - console.log("AxExtensionAbility onConnect"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AxExtensionAbility onConnect'); + } }; ``` @@ -110,8 +112,10 @@ onDisconnect(): void; **示例:** ```ts -onDisconnect(): void { - console.log("AxExtensionAbility onDisconnect"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onDisconnect() { + console.log('AxExtensionAbility onDisconnect'); + } }; ``` @@ -127,15 +131,17 @@ onAccessibilityEvent(event: AccessibilityEvent): void; | 参数名 | 参数类型 | 必填 | 说明 | | ----- | ---------------------------------------- | ---- | --------------- | -| event | [AccessibilityEvent](accessibilityevent) | 是 | 无障碍事件回调函数。无返回值。 | +| event | [AccessibilityEvent](#accessibilityevent) | 是 | 无障碍事件回调函数。无返回值。 | **示例:** ```ts -onAccessibilityEvent(event: AccessibilityEvent): void { - console.log("AxExtensionAbility onAccessibilityEvent"); - if (event.eventType == 'click') { - console.log("AxExtensionAbility onAccessibilityEvent: click"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onAccessibilityEvent(event) { + console.log('AxExtensionAbility onAccessibilityEvent'); + if (event.eventType == 'click') { + console.log('AxExtensionAbility onAccessibilityEvent: click'); + } } }; ``` @@ -157,12 +163,14 @@ onKeyEvent(keyEvent: KeyEvent): boolean; **示例:** ```ts -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { - console.log("AxExtensionAbility onKeyEvent"); - if (keyEvent.keyCode == 22) { - console.log("AxExtensionAbility onKeyEvent: intercept 22"); - return true; +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onKeyEvent(keyEvent) { + console.log('AxExtensionAbility onKeyEvent'); + if (keyEvent.keyCode == 22) { + console.log('AxExtensionAbility onKeyEvent: intercept 22'); + return true; + } + return false; } - return false; }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md index 6c509570ae5161f40d308c34f6ac4d028071c741..ee13cd0a36bab93aae06edef41bb8e7f3180ead1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md @@ -18,27 +18,21 @@ import batteryInfo from '@ohos.batteryInfo'; **系统能力**:SystemCapability.PowerManager.BatteryManager.Core -| 名称 | 类型 | 可读 | 可写 | 描述 | -| ----------------------------------------- | ---------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| batterySOC | number | 是 | 否 | 表示当前设备剩余电池电量百分比。 | -| chargingStatus | [BatteryChargeState](#batterychargestate) | 是 | 否 | 表示当前设备电池的充电状态。 | -| healthStatus | [BatteryHealthState](#batteryhealthstate) | 是 | 否 | 表示当前设备电池的健康状态。 | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | 是 | 否 | 表示当前设备连接的充电器类型。 | -| voltage | number | 是 | 否 | 表示当前设备电池的电压,单位微伏。 | -| technology | string | 是 | 否 | 表示当前设备电池的技术型号。 | -| batteryTemperature | number | 是 | 否 | 表示当前设备电池的温度,单位0.1摄氏度。 | -| isBatteryPresent7+ | boolean | 是 | 否 | 表示当前设备是否支持电池或者电池是否在位。 | -| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | 是 | 否 | 表示当前设备电池电量的等级。 | -| estimatedRemainingChargeTime9+ | number | 是 | 否 | 表示当前设备充满电的预估时间,单位毫秒。 | -| totalEnergy9+ | number | 是 | 否 | 表示当前设备电池的总容量,单位毫安时。此接口为系统接口,三方应用不支持调用。 | -| nowCurrent9+ | number | 是 | 否 | 表示当前设备电池的电流,单位毫安。此接口为系统接口,三方应用不支持调用。 | -| remainingEnergy9+ | number | 是 | 否 | 表示当前设备电池的剩余容量,单位毫安时。此接口为系统接口,三方应用不支持调用。 | - -- 示例: - ```js - import batteryInfo from '@ohos.batteryInfo'; - var batterySoc = batteryInfo.batterySOC; - ``` +| 名称 | 类型 | 可读 | 可写 | 描述 | +| ----------------------------------------- | ---------------------------------------------- | ---- | ---- | ---------------------------------------------------------- | +| batterySOC | number | 是 | 否 | 表示当前设备剩余电池电量百分比。 | +| chargingStatus | [BatteryChargeState](#batterychargestate) | 是 | 否 | 表示当前设备电池的充电状态。 | +| healthStatus | [BatteryHealthState](#batteryhealthstate) | 是 | 否 | 表示当前设备电池的健康状态。 | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | 是 | 否 | 表示当前设备连接的充电器类型。 | +| voltage | number | 是 | 否 | 表示当前设备电池的电压,单位微伏。 | +| technology | string | 是 | 否 | 表示当前设备电池的技术型号。 | +| batteryTemperature | number | 是 | 否 | 表示当前设备电池的温度,单位0.1摄氏度。 | +| isBatteryPresent7+ | boolean | 是 | 否 | 表示当前设备是否支持电池或者电池是否在位。 | +| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | 是 | 否 | 表示当前设备电池电量的等级。 | +| estimatedRemainingChargeTime9+ | number | 是 | 否 | 表示当前设备充满电的预估时间,单位毫秒。 | +| totalEnergy9+ | number | 是 | 否 | 表示当前设备电池的总容量,单位毫安时。此接口为系统接口。 | +| nowCurrent9+ | number | 是 | 否 | 表示当前设备电池的电流,单位毫安。此接口为系统接口。 | +| remainingEnergy9+ | number | 是 | 否 | 表示当前设备电池的剩余容量,单位毫安时。此接口为系统接口。 | ## BatteryPluggedType @@ -105,22 +99,22 @@ import batteryInfo from '@ohos.batteryInfo'; ## CommonEventBatteryChangedCode9+ -表示COMMON_EVENT_BATTERY_CHANGED通用事件的键代码。 +表示COMMON_EVENT_BATTERY_CHANGED通用事件附加信息的查询键。 **系统能力**:SystemCapability.PowerManager.BatteryManager.Core | 名称 | 默认值 | 描述 | | -------------------- | ------ | -------------------------------------------------- | -| EXTRA_SOC | 0 | 表示剩余电池电量百分比的键代码。 | -| EXTRA_VOLTAGE | 1 | 表示当前设备电池电压的键代码。 | -| EXTRA_TEMPERATURE | 2 | 表示当前设备电池温度的键代码。 | -| EXTRA_HEALTH_STATE | 3 | 表示当前设备电池健康状态的键代码。 | -| EXTRA_PLUGGED_TYPE | 4 | 表示当前设备连接的充电器类型的键代码。 | -| EXTRA_MAX_CURRENT | 5 | 表示当前设备电池最大电流的键代码。 | -| EXTRA_MAX_VOLTAGE | 6 | 表示当前设备电池最大电压的键代码。 | -| EXTRA_CHARGE_STATE | 7 | 表示当前设备电池充电状态的键代码。 | -| EXTRA_CHARGE_COUNTER | 8 | 表示当前设备电池充电次数的键代码。 | -| EXTRA_PRESENT | 9 | 表示当前设备是否支持电池或者电池是否在位的键代码。 | -| EXTRA_TECHNOLOGY | 10 | 表示当前设备电池技术型号的键代码。 | +| EXTRA_SOC | 0 | 表示剩余电池电量百分比的查询键。 | +| EXTRA_VOLTAGE | 1 | 表示当前设备电池电压的查询键。 | +| EXTRA_TEMPERATURE | 2 | 表示当前设备电池温度的查询键。 | +| EXTRA_HEALTH_STATE | 3 | 表示当前设备电池健康状态的查询键。 | +| EXTRA_PLUGGED_TYPE | 4 | 表示当前设备连接的充电器类型的查询键。 | +| EXTRA_MAX_CURRENT | 5 | 表示当前设备电池最大电流的查询键。 | +| EXTRA_MAX_VOLTAGE | 6 | 表示当前设备电池最大电压的查询键。 | +| EXTRA_CHARGE_STATE | 7 | 表示当前设备电池充电状态的查询键。 | +| EXTRA_CHARGE_COUNTER | 8 | 表示当前设备电池充电次数的查询键。 | +| EXTRA_PRESENT | 9 | 表示当前设备是否支持电池或者电池是否在位的查询键。 | +| EXTRA_TECHNOLOGY | 10 | 表示当前设备电池技术型号的查询键。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..63b0af54c55ab3320817c1d2fd758cb047d3ffa5 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -0,0 +1,287 @@ +# 耗电统计 + +该模块提供软硬件耗电统计信息的查询接口。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> +> - 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> - 本模块接口为系统接口。 + +## 导入模块 + +```js +import batteryStats from '@ohos.batteryStatistics'; +``` + +## batteryStats.getBatteryStats + +getBatteryStats(): Promise + +获取耗电信息列表。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------- | ------------------------------- | +| Promise> | Promise对象,返回耗电信息列表。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +batteryStats.getBatteryStats() +.then(data => { + console.info('battery statistics info: ' + data); +}) +.catch(err => { + console.error('get battery statisitics failed, err: ' + err); +}); +``` + +## batteryStats.getBatteryStats + +getBatteryStats(callback: AsyncCallback): void + +获取耗电信息列表。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback> | 是 | 回调函数。当获取耗电信息列表成功,err为undefined,data为获取到的Array<[BatteryStatsInfo](#batterystatsinfo)>>;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +batteryStats.getBatteryStats((err, data) => { + if (typeof err === 'undefined') { + console.info('battery statistics info: ' + data); + } else { + console.error('get battery statisitics failed, err: ' + err); + } +}); +``` + +## batteryStats.getAppPowerValue + +getAppPowerValue(uid: number): number + +获取应用的耗电量。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------- | +| uid | number | 是 | 应用的UID。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | --------------------------------- | +| number | UID对应应用的耗电量,单位毫安时。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +try { + var value = batteryStats.getAppPowerValue(10021); + console.info('battery statistics value of app is: ' + value); +} catch(err) { + console.error('get battery statisitics value of app failed, err: ' + err); +} +``` + +## batteryStats.getAppPowerPercent + +getAppPowerPercent(uid: number): number + +获取应用的耗电百分比。 + +**系统能力:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------- | +| uid | number | 是 | 应用的UID。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------- | +| number | UID对应应用的耗电百分比。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +try { + var percent = batteryStats.getAppPowerPercent(10021); + console.info('battery statistics percent of app is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of app failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerValue + +getHardwareUnitPowerValue(type: ConsumptionType): number + +根据耗电类型获取硬件单元的耗电量。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | 是 | 电量消耗类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------------------ | +| number | 电量消耗类型对应硬件的耗电量,单位毫安时。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +try { + var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerPercent + +getHardwareUnitPowerPercent(type: ConsumptionType): number + +根据耗电类型获取硬件单元的耗电百分比。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | 是 | 电量消耗类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------------- | +| number | 电量消耗类型对应硬件的耗电百分比。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-batteryStatistics.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4600101 | 连接服务失败。 | + +**示例:** + +```js +try { + var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## BatteryStatsInfo + +设备的耗电信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +### 属性 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ----------------------------------- | ---- | ---- | ---------------------- | +| uid | number | 是 | 否 | 耗电信息相关的UID。 | +| type | [ConsumptionType](#consumptiontype) | 是 | 否 | 耗电信息相关的类型。 | +| power | number | 是 | 否 | 耗电的值,单位毫安时。 | + +## ConsumptionType + +表示电量消耗类型的枚举值。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.PowerManager.BatteryStatistics + +| 名称 | 值 | 说明 | +| -------------------------- | ---- | ----------------------------- | +| CONSUMPTION_TYPE_INVALID | -17 | 表示电量消耗类型未知。 | +| CONSUMPTION_TYPE_APP | -16 | 表示应用消耗的电量类型。 | +| CONSUMPTION_TYPE_BLUETOOTH | -15 | 表示蓝牙消耗的电量类型。 | +| CONSUMPTION_TYPE_IDLE | -14 | 表示CPU空闲时消耗的电量类型。 | +| CONSUMPTION_TYPE_PHONE | -13 | 表示通话来电消耗的电量类型。 | +| CONSUMPTION_TYPE_RADIO | -12 | 表示无线通讯消耗的电量类型。 | +| CONSUMPTION_TYPE_SCREEN | -11 | 表示屏幕消耗的电量类型。 | +| CONSUMPTION_TYPE_USER | -10 | 表示用户消耗的电量类型。 | +| CONSUMPTION_TYPE_WIFI | -9 | 表示无线网消耗的电量类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-brightness.md b/zh-cn/application-dev/reference/apis/js-apis-brightness.md index e313d9fafc58bfd6e787c37aea890833f4965c7a..e9fc5ba13a49585759aa94f62b4668db60a58f30 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-brightness.md +++ b/zh-cn/application-dev/reference/apis/js-apis-brightness.md @@ -3,8 +3,10 @@ 该模块提供屏幕亮度的设置接口。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - +> +> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> - 本模块接口为系统接口。 ## 导入模块 @@ -18,18 +20,30 @@ setValue(value: number): void 设置系统的屏幕亮度。 -此接口为系统接口,三方应用不支持调用。 +**系统接口:** 此接口为系统接口。 **系统能力:** SystemCapability.PowerManager.DisplayPowerManager **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------- | -| value | number | 是 | 亮度的值(0~255) | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------------------- | +| value | number | 是 | 亮度的值。范围:0~255。 | + +**错误码:** + +以下错误码的详细介绍请参见[屏幕亮度错误码](../errorcodes/errorcode-brightness.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4700101 | 连接服务失败。 | **示例:** ```js -brightness.setValue(128); +try { + brightness.setValue(128); +} catch(err) { + console.error('set brightness failed, err: ' + err); +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md index b6f71f05e5f2b8e22c5b2887f0faf87b8ea74cce..6b86a4f7826a6b00b69b241a3ccfdb261488d7b6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -22,6 +22,8 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callba **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -71,6 +73,8 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -121,6 +125,8 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -173,6 +179,8 @@ disableAdmin(admin: Want, callback: AsyncCallback\): void **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -214,6 +222,8 @@ disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -256,6 +266,8 @@ disableAdmin(admin: Want, userId?: number): Promise\ **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -295,8 +307,12 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void 以异步方法根据给定的包名将设备超级管理员应用去激活,使用Callback形式返回是否去激活成功。 +**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -331,8 +347,12 @@ disableSuperAdmin(bundleName: String): Promise\ 以异步方法根据给定的包名将设备超级管理员应用去激活,使用Promise形式返回是否去激活成功。 +**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -370,6 +390,8 @@ isAdminEnabled(admin: Want, callback: AsyncCallback\): void **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -409,6 +431,8 @@ isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -441,6 +465,8 @@ isAdminEnabled(admin: Want, userId?: number): Promise\ **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -476,6 +502,8 @@ isSuperAdmin(bundleName: String, callback: AsyncCallback\): void **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -504,6 +532,8 @@ isSuperAdmin(bundleName: String): Promise\ **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数**: | 参数名 | 类型 | 必填 | 说明 | @@ -559,14 +589,12 @@ let wantTemp = { }; enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { if (error != null) { - console.log("error occurs" + error); + console.log("error code:" + error.code); return; } - mgr.setDateTime(wantTemp, 1526003846000, (error, value) => { + mgr.setDateTime(wantTemp, 1526003846000, (error) => { if (error != null) { - console.log(error); - } else { - console.log(value); + console.log("error code:" + error.code); } }); }); @@ -603,24 +631,26 @@ let wantTemp = { abilityName: "abilityName", }; enterpriseDeviceManager.getDeviceSettingsManager().then((mgr) => { - mgr.setDateTime(wantTemp, 1526003846000).then((value) => { - console.log(value); - }).catch((error) => { - console.log(error); + mgr.setDateTime(wantTemp, 1526003846000).catch((error) => { + console.log("error code:" + error.code); }) }).catch((error) => { - console.log(error); + console.log("error code:" + error.code); }) ``` ## enterpriseDeviceManager.setEnterpriseInfo -setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCallback<boolean>): void +setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCallback\;): void 设置设备管理员应用的企业信息,使用callback形式返回是否设置成功。 +**需要权限:** ohos.permission.SET_ENTERPRISE_INFO + **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -659,12 +689,16 @@ enterpriseDeviceManager.setEnterpriseInfo(wantTemp, enterpriseInfo, error => { ## enterpriseDeviceManager.setEnterpriseInfo -setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise<boolean> +setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\; 设置设备管理员应用的企业信息,使用Promise形式返回是否设置成功。 +**需要权限:** ohos.permission.SET_ENTERPRISE_INFO + **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -710,6 +744,8 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -750,6 +786,8 @@ getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -791,10 +829,12 @@ subscribeManagedEvent(admin: Want, managedEvents: Array\, callback 订阅系统管理事件。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN +**需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -824,10 +864,12 @@ subscribeManagedEvent(admin: Want, managedEvents: Array\): Promise 订阅系统管理事件。使用Promise异步回调。 -**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN +**需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -861,10 +903,12 @@ unsubscribeManagedEvent(admin: Want, managedEvents: Array\, callba 取消订阅系统管理事件。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN +**需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -894,10 +938,12 @@ unsubscribeManagedEvent(admin: Want, managedEvents: Array\): Promi 取消订阅系统管理事件。使用callback异步回调。 -**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN +**需要权限:** ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md index d15b220e35337fa4b32c45cdb2ece722bba2af5f..256ecd6164f1249d344049794a850002a13d2a6d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @@ -32,6 +32,8 @@ setDateTime(admin: Want, time: number, callback: AsyncCallback\): void **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -81,6 +83,8 @@ setDateTime(admin: Want, time: number): Promise\ **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager +**系统API**: 此接口为系统接口。 + **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-power.md b/zh-cn/application-dev/reference/apis/js-apis-power.md index 4f0bbc49c9627e1280a8a78f7befc241c048cf00..66fef974ce81fdcf5a682b13157fd3e74dc02feb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-power.md +++ b/zh-cn/application-dev/reference/apis/js-apis-power.md @@ -5,21 +5,19 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 ```js import power from '@ohos.power'; ``` +## power.shutdown -## power.shutdownDevice - -shutdownDevice(reason: string): void +shutdown(reason: string): void 系统关机。 -此接口为系统接口,三方应用不支持调用。 +**系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.REBOOT @@ -31,135 +29,191 @@ shutdownDevice(reason: string): void | ------ | ------ | ---- | ----- | | reason | string | 是 | 关机原因。 | +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | + **示例:** ```js -power.shutdownDevice("shutdown_test"); -console.info('power_shutdown_device_test success') +try { + power.shutdown('shutdown_test'); +} catch(err) { + console.error('shutdown failed, err: ' + err); +} ``` +## power.reboot9+ -## power.rebootDevice - -rebootDevice(reason: string): void +reboot(reason: string): void 重启设备。 +**系统接口:** 此接口为系统接口。 + **需要权限:** ohos.permission.REBOOT **系统能力:** SystemCapability.PowerManager.PowerManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ----- | -| reason | string | 是 | 重启原因。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| reason | string | 是 | 重启原因。 | + +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | **示例:** ```js -power.rebootDevice("reboot_test"); -console.info('power_reboot_device_test success') +try { + power.reboot('reboot_test'); +} catch(err) { + console.error('reboot failed, err: ' + err); +} ``` +## power.isActive9+ -## power.isScreenOn +isActive(): boolean -isScreenOn(callback: AsyncCallback<boolean>): void - -检测当前设备的亮灭屏状态。 +检测当前设备是否处于活动状态。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core -**参数:** +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<boolean> | 是 | 指定的callback回调方法,用于获取返回值。
callback返回值:亮屏返回true,灭屏返回false。 | +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | **示例:** ```js -power.isScreenOn((error, screenOn) => { - if (typeof error === "undefined") { - console.info('screenOn status is ' + screenOn); - } else { - console.log('error: ' + error); - } -}) +try { + var isActive = power.isActive(); + console.info('power is active: ' + isActive); +} catch(err) { + console.error('check active status failed, err: ' + err); +} ``` +## power.wakeup9+ -## power.isScreenOn +wakeup(detail: string): void -isScreenOn(): Promise<boolean> +唤醒设备。 -检测当前设备的亮灭屏状态。 +**系统接口:** 此接口为系统接口。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core -**返回值:** -| 类型 | 说明 | -| ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise实例,用于异步获取返回值,亮屏返回true,灭屏返回false。 | +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| detail | string | 是 | 唤醒原因。 | + +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | **示例:** ```js -power.isScreenOn() -.then(screenOn => { - console.info('screenOn status is ' + screenOn); -}) -.catch(error => { - console.log('error: ' + error); -}) +try { + power.wakeup('wakeup_test'); +} catch(err) { + console.error('wakeup failed, err: ' + err); +} ``` -## power.wakeupDevice9+ +## power.suspend9+ -wakeupDevice(detail: string): void +suspend(): void -唤醒设备。 +休眠设备。 -此接口为系统接口,三方应用不支持调用。 +**系统接口:** 此接口为系统接口。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core -**参数:** +**错误码:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------- | -| detail | string | 是 | 唤醒原因。 | +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | **示例:** ```js -power.wakeupDevice("application"); -console.info('power_wakeup_device_test success') +try { + power.suspend(); +} catch(err) { + console.error('suspend failed, err: ' + err); +} ``` -## power.suspendDevice9+ +## power.getPowerMode9+ -suspendDevice(): void +getPowerMode(): DevicePowerMode -休眠设备。 +获取当前设备的电源模式。 -此接口为系统接口,三方应用不支持调用。 +**需要权限:** ohos.permission.POWER_OPTIMIZATION **系统能力:** SystemCapability.PowerManager.PowerManager.Core +**返回值:** + +| 类型 | 说明 | +| ------------------------------------ | ---------- | +| [DevicePowerMode](#devicepowermode9) | 电源模式。 | + +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | + **示例:** ```js -power.suspendDevice(); -console.info('power_suspend_device_test success') +try { + var mode = power.getPowerMode(); + console.info('power mode: ' + mode); +} catch(err) { + console.error('get power mode failed, err: ' + err); +} ``` -## power.getPowerMode9+ +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void -getPowerMode(callback: AsyncCallback<DevicePowerMode>): void +设置当前设备的电源模式。使用callback异步回调。 -获取当前设备的电源模式。 +**系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.POWER_OPTIMIZATION @@ -169,114 +223,149 @@ getPowerMode(callback: AsyncCallback<DevicePowerMode>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<DevicePowerMode> | 是 | 指定的callback回调方法,用于获取返回值。
callback返回值:[DevicePowerMode](#devicepowermode9)。 | +| mode | [DevicePowerMode](#devicepowermode9) | 是 | 电源模式。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置电源模式成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | **示例:** ```js -power.getPowerMode((error, mode) => { - if (typeof error === "undefined") { - console.info('power mode is ' + mode); +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, err => { + if (typeof err === 'undefined') { + console.info('set power mode to MODE_PERFORMANCE'); } else { - console.log('error: ' + error); + console.error('set power mode failed, err: ' + err); } -}) +}); ``` +## power.setPowerMode9+ -## power.getPowerMode9+ +setPowerMode(mode: DevicePowerMode): Promise<void> -getPowerMode(): Promise<DevicePowerMode> +设置当前设备的电源模式。使用Promise异步回调。 -获取当前设备的电源模式。 +**系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.POWER_OPTIMIZATION **系统能力:** SystemCapability.PowerManager.PowerManager.Core +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ---------- | +| mode | [DevicePowerMode](#devicepowermode9) | 是 | 电源模式。 | + **返回值:** -| 类型 | 说明 | -| ------------------------------ | ------------------------------------------------------------ | -| Promise<DevicePowerMode> | Promise实例,用于异步获取返回值,[DevicePowerMode](#devicepowermode9)。 | +| 类型 | 说明 | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[系统电源管理错误码](../errorcodes/errorcode-power.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 链接服务失败。 | **示例:** ```js -power.getPowerMode() -.then(mode => { - console.info('power mode is ' + mode); -}) -.catch(error => { - console.log('error: ' + error); +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) +.then(() => { + console.info('set power mode to MODE_PERFORMANCE'); }) +.catch(err => { + console.error('set power mode failed, err: ' + err); +}); ``` -## power.setPowerMode9+ +## power.rebootDevice(deprecated) -setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void +rebootDevice(reason: string): void -设置当前设备的电源模式。 +> 从API version 9开始不再维护,建议使用[power.reboot](#powerreboot9)替代。 -此接口为系统接口,三方应用不支持调用。 +重启设备。 -**需要权限:** ohos.permission.POWER_OPTIMIZATION +**需要权限:** ohos.permission.REBOOT **系统能力:** SystemCapability.PowerManager.PowerManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | ------------------------ | -| mode | [DevicePowerMode](#devicepowermode9) | 是 | 电源模式。 | -| callback | AsyncCallback<void> | 是 | 指定的callback回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----- | +| reason | string | 是 | 重启原因。 | **示例:** ```js -power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, error => { - if (typeof error === "undefined") { - console.info('set power mode to MODE_PERFORMANCE'); - } else { - console.log('error: ' + error); - } -}) +power.rebootDevice('reboot_test'); ``` +## power.isScreenOn(deprecated) -## power.setPowerMode9+ - -setPowerMode(mode: DevicePowerMode): Promise<void> - -设置当前设备的电源模式。 +isScreenOn(callback: AsyncCallback<boolean>): void -此接口为系统接口,三方应用不支持调用。 +> 从API version 9开始不再维护,建议使用[power.isActive](#powerisactive9)替代。 -**需要权限:** ohos.permission.POWER_OPTIMIZATION +检测当前设备的亮灭屏状态。使用callback异步回调。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------ | ---- | ---------- | -| mode | [DevicePowerMode](#devicepowermode9) | 是 | 电源模式。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检测成功,err为undefined,data为获取到的亮灭屏状态,返回true表示梁平,返回false表示灭屏;否则为错误对象。 | -**返回值:** +**示例:** -| 类型 | 说明 | -| ------------------- | ------------- | -| Promise<void> | Promise实例。 | +```js +power.isScreenOn((err, data) => { + if (typeof err === 'undefined') { + console.info('screen on status is ' + data); + } else { + console.error('check screen status failed, err: ' + err); + } +}) +``` + +## power.isScreenOn(deprecated) + +isScreenOn(): Promise<boolean> + +> 从API version 9开始不再维护,建议使用[power.isActive](#powerisactive9)替代。 + +检测当前设备的亮灭屏状态。使用Promise异步回调。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +**返回值:** +| 类型 | 说明 | +| ---------------------- | -------------------------------------------------- | +| Promise<boolean> | Promise对象。返回true表示亮屏;返回false表示灭屏。 | **示例:** ```js -power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) -.then(() => { - console.info('set power mode to MODE_PERFORMANCE'); +power.isScreenOn() +.then(data => { + console.info('screen on status is ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.error('check screen status failed, err: ' + err); }) ``` @@ -286,7 +375,6 @@ power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) **系统能力:** SystemCapability.PowerManager.PowerManager.Core - | 名称 | 默认值 | 描述 | | ----------------------- | ------ | ---------------------- | | MODE_NORMAL | 600 | 表示标准模式,默认值。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-prompt.md b/zh-cn/application-dev/reference/apis/js-apis-prompt.md index b757e22f002c9b512580c886f4371ad1a56cbc7f..e27e59cc59adff21df45050006848f3d5824c852 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-prompt.md +++ b/zh-cn/application-dev/reference/apis/js-apis-prompt.md @@ -46,7 +46,7 @@ prompt.showToast({ | 名称 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 是 | 显示的文本信息。 | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 显示的文本信息。 | | duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 | | bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置。 | @@ -147,8 +147,8 @@ prompt.showDialog({ | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 否 | 标题文本。 | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 否 | 内容文本。 | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 标题文本。 | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 内容文本。 | | buttons | Array | 否 | 对话框中按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 | ## ShowDialogSuccessResponse @@ -256,7 +256,7 @@ prompt.showActionMenu({ | 名称 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 否 | 标题文本。 | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 否 | 标题文本。 | | buttons | Array<[Button](#button)> | 是 | 菜单中菜单项按钮的数组,结构为:{text:'button', color: '\#666666'},支持1-6个按钮。大于6个按钮时弹窗不显示。 | ## ActionMenuSuccessResponse @@ -277,6 +277,6 @@ prompt.showActionMenu({ | 名称 | 类型 | 必填 | 说明 | | ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 是 | 按钮文本内容。 | -| color | string\| [Resource](../arkui-ts/ts-types.md#resource类型)9+ | 是 | 按钮文本颜色。 | +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 按钮文本内容。 | +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | 是 | 按钮文本颜色。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md index 1b7bfab5917b1be6943cc9e107b386426551161c..a0bde36e929a11bbbedd7cd63e640bf795a45424 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md @@ -1,95 +1,205 @@ -# Runninglock锁 +# RunningLock锁 -该模块主要提供Runninglock锁相关操作的接口,包括创建、查询、持锁、释放锁等操作。 +该模块主要提供RunningLock锁相关操作的接口,包括创建、查询、持锁、释放锁等操作。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 -``` +```js import runningLock from '@ohos.runningLock'; ``` +## runningLock.isSupported9+ -## RunningLockType +isSupported(type: RunningLockType): boolean; -RunningLock锁的类型。 +查询系统是否支持该类型的锁。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.PowerManager.PowerManager.Core +**系统能力:** SystemCapability.PowerManager.PowerManager.Core -| 名称 | 默认值 | 描述 | -| ------------------------ | ---- | ------------------- | -| BACKGROUND | 1 | 阻止系统休眠的锁。 | -| PROXIMITY_SCREEN_CONTROL | 2 | 通过接近或者远离状态来控制亮灭屏的锁。 | +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | 是 | 需要查询的锁的类型。 | -## isRunningLockTypeSupported +**返回值:** -isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void +| 类型 | 说明 | +| ------- | --------------------------------------- | +| boolean | 返回true表示支持,返回false表示不支持。 | -查询系统是否支持该类型的锁。 +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | + +**示例:** + +```js +try { + var isSupported = runningLock.isSupported(runningLock.RunningLockType.BACKGROUND); + console.info('BACKGROUND type supported: ' + isSupported); +} catch(err) { + console.error('check supported failed, err: ' + err); +} +``` + +## runningLock.create9+ + +createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void + +创建RunningLock锁。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core +**需要权限:** ohos.permission.RUNNING_LOCK + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| type | RunningLockType | 是 | 需要查询的锁的类型。 | -| callback | AsyncCallback<boolean> | 是 | 指定的callback回调方法,用于获取返回值。
callback返回值:支持返回true,不支持返回false。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | 是 | 锁的名字。 | +| type | [RunningLockType](#runninglocktype) | 是 | 要创建的锁的类型。 | +| callback | AsyncCallback<[RunningLock](#runninglock)> | 是 | 回调函数。当创建锁成功,err为undefined,data为创建的RunningLock;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|----------| +| 4900101 | 连接服务器失败。 | **示例:** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { - if (typeof error === "undefined") { - console.info('BACKGROUND support status is ' + supported); +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); } else { - console.log('error: ' + error); + console.error('create running lock failed, err: ' + err); } +}); +``` + +## runningLock.create9+ + +createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> + +创建RunningLock锁。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +**需要权限:** ohos.permission.RUNNING_LOCK + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | 是 | 锁的名字。 | +| type | [RunningLockType](#runninglocktype) | 是 | 要创建的锁的类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise对象,返回RunningLock锁对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|----------| +| 4900101 | 连接服务器失败。 | + +**示例:** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); }) +.catch(err => { + console.error('create running lock failed, error: ' + err); +}); ``` +## runningLock.isRunningLockTypeSupported(deprecated) -## isRunningLockTypeSupported +isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void -isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> +> 从API version 9开始不再维护,建议使用[runningLock.isSupported](#runninglockissupported9)替代。 -查询系统是否支持该类型的锁。 +查询系统是否支持该类型的锁。使用callback异步回调。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| type | [RunningLockType](#runninglocktype) | 是 | 需要查询的锁的类型。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当查询成功,err为undefined,data为获取到的支持情况,返回true表示支持,返回false表示不支持;否则为错误对象。 | + +**示例:** + +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (err, data) => { + if (typeof err === 'undefined') { + console.info('BACKGROUND lock support status: ' + data); + } else { + console.log('check BACKGROUND lock support status failed, err: ' + err); + } +}); +``` + +## runningLock.isRunningLockTypeSupported(deprecated) + +isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> + +> 从API version 9开始不再维护,建议使用[runningLock.isSupported](#runninglockissupported9)替代。 + +查询系统是否支持该类型的锁。使用Promise异步回调。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | --------------- | ---- | ---------- | -| type | RunningLockType | 是 | 需要查询的锁的类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | 是 | 需要查询的锁的类型。 | **返回值:** -| 类型 | 说明 | -| ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise实例,用于异步获取返回值,支持返回true,不支持返回false。 | +| 类型 | 说明 | +| ---------------------- | ---------------------------------------------------- | +| Promise<boolean> | Promise对象。返回true表示支持;返回false表示不支持。 | **示例:** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) -.then(supported => { - console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) +.then(data => { + console.info('BACKGROUND lock support status: ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.log('check BACKGROUND lock support status failed, err: ' + err); }); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void +> 从API version 9开始不再维护,建议使用[runningLock.create](#runninglockcreate9)替代。 + 创建RunningLock锁。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core @@ -98,34 +208,31 @@ createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&l **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| name | string | 是 | 锁的名字。 | -| type | RunningLockType | 是 | 要创建的锁的类型。 | -| callback | AsyncCallback<[RunningLock](#runninglock)> | 是 | 指定的callback回调方法,用于获取返回的RunningLock锁对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | 是 | 锁的名字。 | +| type | [RunningLockType](#runninglocktype) | 是 | 要创建的锁的类型。 | +| callback | AsyncCallback<[RunningLock](#runninglock)> | 是 | 回调函数。当创建锁成功,err为undefined,data为创建的RunningLock;否则为错误对象。 | **示例:** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { - if (typeof error === "undefined") { - console.log('create runningLock test error: ' + error); +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); } else { - var used = lockIns.isUsed(); - console.info('runninglock is used: ' + used); - lockIns.lock(500); - used = lockIns.isUsed(); - console.info('after lock runninglock is used ' + used); + console.error('create running lock failed, err: ' + err); } -}) +}); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> -创建Runninglock锁。 +> 从API version 9开始不再维护,建议使用[runningLock.create](#runninglockcreate9)替代。 + +创建RunningLock锁。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core @@ -133,39 +240,157 @@ createRunningLock(name: string, type: RunningLockType): Promise<RunningLock&g **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | --------------- | ---- | --------- | -| name | string | 是 | 锁的名字。 | -| type | RunningLockType | 是 | 要创建的锁的类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | 是 | 锁的名字。 | +| type | [RunningLockType](#runninglocktype) | 是 | 要创建的锁的类型。 | **返回值:** | 类型 | 说明 | -| ---------------------------------------- | ---------------------------------- | -| Promise<[RunningLock](#runninglock)> | Promise实例,用于异步获取返回的RunningLock锁对象。 | +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise对象,返回RunningLock锁对象。 | **示例:** +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.log('create running lock failed, err: ' + err); +}); ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - console.info('create runningLock success'); + +## RunningLock + +阻止系统休眠的锁。 + +### hold9+ + +hold(timeout: number): void + +锁定和持有RunningLock。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +**需要权限:** ohos.permission.RUNNING_LOCK + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | 否 | 锁定和持有RunningLock的时长,单位:毫秒。 | + +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|----------| +| 4900101 | 连接服务器失败。 | + +**示例:** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.hold(500); + console.info('hold running lock success'); + } catch(err) { + console.error('hold running lock failed, err: ' + err); + } }) -.catch(error => { - console.log('create runningLock test error: ' + error); +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### unhold9+ + +unhold(): void + +释放RunningLock锁。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +**需要权限:** ohos.permission.RUNNING_LOCK + +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|----------| +| 4900101 | 连接服务器失败。 | + +**示例:** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.unhold(); + console.info('unhold running lock success'); + } catch(err) { + console.error('unhold running lock failed, err: ' + err); + } }) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); ``` +### isHolding9+ -## RunningLock +isHolding(): boolean -阻止系统休眠的锁。 +查询当前RunningLock是持有状态还是释放状态。 +**系统能力:** SystemCapability.PowerManager.PowerManager.Core -### lock +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示当前RunningLock是持有状态,返回false表示当前RunningLock是释放状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[RunningLock锁错误码](../errorcodes/errorcode-runninglock.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4900101 | 连接服务失败。 | + +**示例:** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + var isHolding = lock.isHolding(); + console.info('check running lock holding status: ' + isHolding); + } catch(err) { + console.error('check running lock holding status failed, err: ' + err); + } +}) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### lock(deprecated) lock(timeout: number): void +> 从API version 9开始不再维护,建议使用[RunningLock.hold](#hold9)替代。 + 锁定和持有RunningLock。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core @@ -180,23 +405,24 @@ lock(timeout: number): void **示例:** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.lock(100) - console.info('create runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.lock(500); + console.info('create running lock and lock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### unlock +### unlock(deprecated) unlock(): void -释放Runninglock锁。 +> 从API version 9开始不再维护,建议使用[RunningLock.unhold](#unhold9)替代。 + +释放RunningLock锁。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core @@ -204,40 +430,52 @@ unlock(): void **示例:** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.unlock() - console.info('create and unLock runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.unlock(); + console.info('create running lock and unlock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### isUsed +### isUsed(deprecated) isUsed(): boolean -查询当前Runninglock是持有状态还是释放状态。 +> 从API version 9开始不再维护,建议使用[RunningLock.isHolding](#isholding9)替代。 + +查询当前RunningLock是持有状态还是释放状态。 **系统能力:** SystemCapability.PowerManager.PowerManager.Core **返回值:** -| 类型 | 说明 | -| ------- | ------------------------------------- | -| boolean | 当前RunningLock是持有状态返回true,释放状态返回false。 | +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示当前RunningLock是持有状态,返回false表示当前RunningLock是释放状态。 | **示例:** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - var used = runningLock.isUsed() - console.info('runningLock used status: ' + used) +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + var isUsed = lock.isUsed(); + console.info('check running lock used status: ' + isUsed); }) -.catch(error => { - console.log('runningLock isUsed test error: ' + error) +.catch(err => { + console.error('check running lock used status failed, err: ' + err); }); ``` + +## RunningLockType + +RunningLock锁的类型。 + +**系统能力:** SystemCapability.PowerManager.PowerManager.Core + +| 名称 | 默认值 | 描述 | +| ------------------------ | ------ | -------------------------------------- | +| BACKGROUND | 1 | 阻止系统休眠的锁。 | +| PROXIMITY_SCREEN_CONTROL | 2 | 通过接近或者远离状态来控制亮灭屏的锁。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-battery.md b/zh-cn/application-dev/reference/apis/js-apis-system-battery.md index 2c4b2dedd6ad05b58909ef2018d0c7abe46743c4..ef6470a146352fde292da777f2061659daed87df 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-battery.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-battery.md @@ -1,9 +1,10 @@ # 电量信息 -> **说明:** -> - 从API Version 6开始,该接口不再维护,推荐使用新接口[`@ohos.batteryInfo`](js-apis-battery-info.md)。 -> -> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +该模块提供充电状态及剩余电量的查询功能。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - 从API Version 6开始不再维护,建议使用[`@ohos.batteryInfo`](js-apis-battery-info.md)替代。 +> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -16,7 +17,7 @@ import battery from '@system.battery'; ## battery.getStatus -getStatus(Object): void +getStatus(options?: GetStatusOptions): void; 获取设备当前的充电状态及剩余电量。 @@ -26,29 +27,35 @@ getStatus(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| success | (data: [BatteryResponse](#batteryresponse)) => void | 否 | 接口调用成功的回调函数。| -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。| -| complete | () => void | 否 | 接口调用结束的回调函数。 | +| options | [GetStatusOptions](#getstatusoptions) | 否 | 包含接口调用结果的对象。 | **示例:** ```js -export default { - getStatus() { - battery.getStatus({ - success: function(data) { - console.log('success get battery level:' + data.level); - }, - fail: function(data, code) { - console.log('fail to get battery level code:' + code + ', data: ' + data); - }, - }); - }, -} +battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.error('fail to get battery level code:' + code + ', data: ' + data); + } +}); ``` +## GetStatusOptions + +包含接口调用结果的对象。 + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BatteryResponse](#batteryresponse)) => void | 否 | 接口调用成功的回调函数,data为[BatteryResponse](#batteryresponse)类型的返回值。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | + ## BatteryResponse +包含充电状态及剩余电量的对象。 + | 参数名 | 类型 | 说明 | | -------- | -------- | -------- | | charging | boolean | 当前电池是否在充电中。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md b/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md index cf8e51aa4d1b60ca58443507a460b53ae55387bc..206440dd74e9e79918932823829a9030b1c245c8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,8 +1,9 @@ # 屏幕亮度 -> **说明:** -> - 从API Version 7 开始,该接口不再维护,推荐使用新接口[`@ohos.brightness`](js-apis-brightness.md)。 -> +该模块提供屏幕亮度和模式的查询、调节接口。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - 从API Version 7 开始不再维护,建议使用[`@ohos.brightness`](js-apis-brightness.md)替代。 > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -16,7 +17,7 @@ import brightness from '@system.brightness'; ## brightness.getValue -getValue(Object): void +getValue(options?: GetBrightnessOptions): void 获得设备当前的屏幕亮度值。 @@ -26,38 +27,25 @@ getValue(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| success | (data: [BrightnessResponse](#brightnessresponse)) => void | 否 | 接口调用成功的回调函数。 | -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | -| complete | () => void | 否 | 接口调用结束的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| value | number | 屏幕亮度,取值为1-255之间的整数。 | - +| options | [GetBrightnessOptions](#getbrightnessoptions) | 否 | 获取屏幕亮度的参数对象。 | **示例:** ```js - export default { - getValue() { - brightness.getValue({ - success: function(data){ - console.log('success get brightness value:' + data.value); - }, - fail: function(data, code) { - console.log('get brightness fail, code: ' + code + ', data: ' + data); - }, - }); - }, - } + brightness.getValue({ + success: function(data) { + console.log('success get brightness value:' + data.value); + }, + fail: function(data, code) { + console.error('get brightness fail, code: ' + code + ', data: ' + data); + } + }); ``` ## brightness.setValue -setValue(Object): void +etValue(options?: SetBrightnessOptions): void 设置设备当前的屏幕亮度值。 @@ -67,33 +55,26 @@ setValue(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 屏幕亮度,值为1-255之间的整数。
- 如果值小于等于0,系统按1处理。
- 如果值大于255,系统按255处理。
- 如果值为小数,系统将处理为整数。例如设置为8.1,系统按8处理。 | -| success | () => void | 否 | 接口调用成功的回调函数。 | -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | -| complete | () => void | 否 | 接口调用结束的回调函数。 | +| options | [SetBrightnessOptions](#setbrightnessoptions) | 否 | 设置屏幕亮度的参数对象。 | **示例:** ```js - export default { - setValue() { - brightness.setValue({ - value: 100, - success: function(){ - console.log('handling set brightness success.'); - }, - fail: function(data, code){ - console.log('handling set brightness value fail, code:' + code + ', data: ' + data); - }, - }); - }, - } + brightness.setValue({ + value: 100, + success: function() { + console.log('handling set brightness success.'); + }, + fail: function(data, code) { + console.error('handling set brightness value fail, code:' + code + ', data: ' + data); + } + }); ``` ## brightness.getMode -getMode(Object): void +getMode(options?: GetBrightnessModeOptions: void 获得当前屏幕亮度模式。 @@ -103,37 +84,25 @@ getMode(Object): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | 否 | 接口调用成功的回调函数。 | -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | -| complete | () => void | 否 | 接口调用结束的回调函数。 | - -success返回值: - -| 参数名 | 类型 | 说明 | -| -------- | -------- | -------- | -| mode | number | 值为0或1:
- 0为手动调节屏幕亮度模式
- 1为自动调节屏幕亮度模式 | +| options | [GetBrightnessModeOptions](#getbrightnessmodeoptions) | 否 | 获取屏幕亮度模式的参数对象。 | **示例:** ```js - export default { - getMode() { - brightness.getMode({ - success: function(data){ - console.log('success get mode:' + data.mode); - }, - fail: function(data, code){ - console.log('handling get mode fail, code:' + code + ', data: ' + data); - }, - }); - }, - } + brightness.getMode({ + success: function(data) { + console.log('success get mode:' + data.mode); + }, + fail: function(data, code){ + console.error('handling get mode fail, code:' + code + ', data: ' + data); + } + }); ``` ## brightness.setMode -setMode(Object): void +setMode(options?: SetBrightnessModeOptions): void 设置设备当前的屏幕亮度模式。 @@ -142,74 +111,118 @@ setMode(Object): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| mode | number | 是 | 值为0或1
- 0为手动调节屏幕亮度。
- 1为自动调节屏幕亮度。 | -| success | () => void | 否 | 接口调用成功的回调函数。 | -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | -| complete | () => void | 否 | 接口调用结束的回调函数。 | +| options | [SetBrightnessModeOptions](#setbrightnessmodeoptions) | 否 | 设置屏幕亮度模式的参数对象。 | **示例:** ```js - export default { - setMode() { - brightness.setMode({ - mode: 1, - success: function(){ - console.log('handling set mode success.'); - }, - fail: function(data, code){ - console.log('handling set mode fail, code:' + code + ', data: ' + data); - }, - }); - }, - } + brightness.setMode({ + mode: 1, + success: function() { + console.log('handling set mode success.'); + }, + fail: function(data, code) { + console.error('handling set mode fail, code:' + code + ', data: ' + data); + } + }); ``` ## brightness.setKeepScreenOn -setKeepScreenOn(Object): void +setKeepScreenOn(options?: SetKeepScreenOnOptions): void + +>从API version 7开始不再维护,建议使用[window.setKeepScreenOn](js-apis-window.md#setkeepscreenon)替代。 设置屏幕是否保持常亮状态,开启常亮模式推荐在onShow()阶段调用。 **系统能力:** SystemCapability.PowerManager.DisplayPowerManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| keepScreenOn | boolean | 是 | 是否保持屏幕常亮。 | -| success | () => void | 否 | 接口调用成功的回调函数。 | -| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。 | -| complete | () => void | 否 | 接口调用结束的回调函数。 | +| options | [SetKeepScreenOnOptions](#setkeepscreenonoptions) | 否 | 设置屏幕常亮的参数对象。 | **示例:** ```js - export default { - setKeepScreenOn() { - brightness.setKeepScreenOn({ - keepScreenOn: true, - success: function () { - console.log('handling set keep screen on success.') - }, - fail: function (data, code) { - console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); - }, - }); - }, - } + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.'); + }, + fail: function (data, code) { + console.error('handling set keep screen on fail, code:' + code + ', data: ' + data); + } + }); ``` -## +## GetBrightnessOptions + +获取屏幕亮度的参数对象。 + +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessResponse](#brightnessresponse)) => void | 否 | 接口调用成功的回调函数。data为[BrightnessResponse](#brightnessresponse)类型的返回值。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | + +## SetBrightnessOptions + +设置屏幕亮度的参数对象。 + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| value | number | 是 | 屏幕亮度,值为1-255之间的整数。
- 如果值小于等于0,系统按1处理。
- 如果值大于255,系统按255处理。
- 如果值为小数,系统将处理为整数。例如设置为8.1,系统按8处理。 | +| success | () => void | 否 | 接口调用成功的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | ## BrightnessResponse +包含屏幕亮度的对象。 + | 名称 | 类型 | 说明 | | -------- | -------- | -------- | -| value | number | 屏幕亮度,取值为1-255之间的整数。 | +| value | number | 屏幕亮度,范围:1到255。 | + +## GetBrightnessModeOptions + +获取屏幕亮度模式的参数对象。 + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | 否 | 接口调用成功的回调函数。data为[BrightnessModeResponse](#brightnessmoderesponse)类型的返回值。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | + +## SetBrightnessModeOptions + +设置屏幕亮度模式的参数对象。 + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | +| mode | number | 是 | 0表示手动调节屏幕亮度模式,1表示自动调节屏幕亮度模式。 | +| success | () => void | 否 | 接口调用成功的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | ## BrightnessModeResponse +包含屏幕亮度模式的对象。 + | 名称 | 类型 | 说明 | | -------- | -------- | -------- | -| mode | number | 值为0或1。
-0为手动调节屏幕亮度模式。
-1为手动调节屏幕亮度模式。 | +| mode | number | 0表示手动调节屏幕亮度模式,1表示自动调节屏幕亮度模式。 | + +## SetKeepScreenOnOptions + +设置屏幕常亮的参数对象。 + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | +| keepScreenOn | boolean | 是 | true表示保持屏幕常亮,false表示取消屏幕常亮。 | +| success | () => void | 否 | 接口调用成功的回调函数。 | +| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 | +| complete | () => void | 否 | 接口调用结束的回调函数。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-thermal.md b/zh-cn/application-dev/reference/apis/js-apis-thermal.md index 4c19beee330fb0ca0b0d4653e35fd4514b925131..8ba540f98137c7ae9990fa53bb1f8e9c605e0567 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-thermal.md +++ b/zh-cn/application-dev/reference/apis/js-apis-thermal.md @@ -5,80 +5,169 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 ```js import thermal from '@ohos.thermal'; ``` +## thermal.registerThermalLevelCallback9+ -## ThermalLevel +registerThermalLevelCallback(callback: Callback<ThermalLevel>): void -热档位信息。 +订阅热档位变化时的回调提醒。 + +**系统能力:** SystemCapability.PowerManager.ThermalManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ------------------------------ | +| callback | Callback<ThermalLevel> | 是 | 回调函数,返回变化后的热档位。 | + +**错误码:** + +以下错误码的详细介绍请参见[耗电统计错误码](../errorcodes/errorcode-thermal.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4800101 | 连接服务失败。 | + +**示例:** + +```js +try { + thermal.registerThermalLevelCallback(level => { + console.info('thermal level is: ' + level); + }); + console.info('register thermal level callback success.'); +} catch(err) { + console.error('register thermal level callback failed, err: ' + err); +} +``` + +## thermal.unregisterThermalLevelCallback9+ + +unregisterThermalLevelCallback(callback?: Callback\): void + +取消订阅热档位变化时的回调提醒。 + +**系统能力:** SystemCapability.PowerManager.ThermalManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ---------------------------------------------- | +| callback | Callback<void> | 可选 | 回调函数,无返回值。不填该参数则取消所有回调。 | + +**错误码:** + +以下错误码的详细介绍请参见[热管理错误码](../errorcodes/errorcode-thermal.md)。 + +| 错误码ID | 错误信息 | +|---------|---------| +| 4800101 | 连接服务失败。 | + +**示例:** + +```js +try { + thermal.unregisterThermalLevelCallback(() => { + console.info('unsubscribe thermal level success.'); + }); + console.info('unregister thermal level callback success.'); +} catch(err) { + console.error('unregister thermal level callback failed, err: ' + err); +} +``` + +## thermal.getLevel9+ + +getLevel(): ThermalLevel + +获取当前热档位信息。 + +**系统能力:** SystemCapability.PowerManager.ThermalManager + +**返回值:** + +| 类型 | 说明 | +| ------------ | ------------ | +| ThermalLevel | 热档位信息。 | + +**错误码:** -**系统能力:** 以下各项对应的系统能力均为SystemCapability.PowerManager.ThermalManager +以下错误码的详细介绍请参见[热管理错误码](../errorcodes/errorcode-thermal.md)。 -| 名称 | 默认值 | 描述 | -| ---------- | ---- | ---------------------------------------- | -| COOL | 0 | 表明设备处于低温的状态,业务执行不受热控的限制。 | -| NORMAL | 1 | 表明设备处于正常工作状态,但温度不低,需要注意是否临近发热状态 | -| WARM | 2 | 表明设备已经进入温热状态,部分无感知业务需要考虑停止或延迟执行。 | -| HOT | 3 | 表明设备已经明显发热,无感知业务应全面停止,其他业务应考虑降规格及负载。 | -| OVERHEATED | 4 | 表明设备已经发热严重,无感知业务应全面停止,主要业务需降低规格及负载。 | -| WARNING | 5 | 表明设备已经发热严重并且即将进入紧急状态,无感知业务应全面停止,主要业务应降低至最低规格。 | -| EMERGENCY | 6 | 表明设备已经进入紧急状态,所有业务应当全面停止工作,可保留部分紧急求助功能。 | +| 错误码ID | 错误信息 | +|---------|---------| +| 4800101 | 连接服务失败。 | +**示例:** + +```js +try { + var level = thermal.getLevel(); + console.info('thermal level is: ' + level); +} catch(err) { + console.error('get thermal level failed, err: ' + err); +} +``` -## thermal.subscribeThermalLevel +## thermal.subscribeThermalLevel(deprecated) subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void +> 从API version 9开始不再维护,建议使用[thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9)替代。 + 订阅热档位变化时的回调提醒。 **系统能力:** SystemCapability.PowerManager.ThermalManager **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<ThermalLevel> | 是 | 指定的callback回调方法,用于获取返回值。
AsyncCallback只返回一个参数,为热档位信息,此时可能会产生告警,可通过`// @ts-ignore`进行抑制。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<ThermalLevel> | 是 | 回调函数。AsyncCallback只返回一个参数,为热档位信息,此时可能会产生告警,可通过`// @ts-ignore`进行抑制。 | **示例:** ```js -var lev = 0; -thermal.subscribeThermalLevel((lev) => { - console.info("Thermal level is: " + lev); -}) +thermal.subscribeThermalLevel((level) => { + console.info('thermal level is: ' + level); +}); ``` -## thermal.unsubscribeThermalLevel +## thermal.unsubscribeThermalLevel(deprecated) unsubscribeThermalLevel(callback?: AsyncCallback\): void +> 从API version 9开始不再维护,建议使用[thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9)替代。 + 取消订阅热档位变化时的回调提醒。 **系统能力:** SystemCapability.PowerManager.ThermalManager **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | --------------------- | -| callback | AsyncCallback<void> | 可选 | 指定的callback回调方法,无返回值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------------------------------- | +| callback | AsyncCallback<void> | 否 | 回调函数,无返回值。不填该参数则取消所有回调。 | **示例:** ```js thermal.unsubscribeThermalLevel(() => { - console.info("Unsubscribe completed."); + console.info('unsubscribe thermal level success.'); }); ``` -## thermal.getThermalLevel +## thermal.getThermalLevel(deprecated) getThermalLevel(): ThermalLevel +> 从API version 9开始不再维护,建议使用[thermal.getLevel](#thermalgetlevel9)替代。 + 获取当前热档位信息。 **系统能力:** SystemCapability.PowerManager.ThermalManager @@ -92,6 +181,22 @@ getThermalLevel(): ThermalLevel **示例:** ```js -var lev = thermal.getThermalLevel(); -console.info("Thermal level is: " + lev); +var level = thermal.getThermalLevel(); +console.info('thermal level is: ' + level); ``` + +## ThermalLevel + +热档位信息。 + +**系统能力:** SystemCapability.PowerManager.ThermalManager + +| 名称 | 默认值 | 描述 | +| ---------- | ------ | ------------------------------------------------------------ | +| COOL | 0 | 表明设备处于低温的状态,业务执行不受热控的限制。 | +| NORMAL | 1 | 表明设备处于正常工作状态,但温度不低,需要注意是否临近发热状态 | +| WARM | 2 | 表明设备已经进入温热状态,部分无感知业务需要考虑停止或延迟执行。 | +| HOT | 3 | 表明设备已经明显发热,无感知业务应全面停止,其他业务应考虑降规格及负载。 | +| OVERHEATED | 4 | 表明设备已经发热严重,无感知业务应全面停止,主要业务需降低规格及负载。 | +| WARNING | 5 | 表明设备已经发热严重并且即将进入紧急状态,无感知业务应全面停止,主要业务应降低至最低规格。 | +| EMERGENCY | 6 | 表明设备已经进入紧急状态,所有业务应当全面停止工作,可保留部分紧急求助功能。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md index 1e6f73189bdcdcd1486b869cd1788513e5a9cddc..aa35794cc466b4e592cedeaa16be6400d9caba9c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uitest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -23,6 +23,99 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest' ``` +## MatchPattern + +控件属性支持的匹配模式。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 值 | 说明 | +| ----------- | ---- | -------------- | +| EQUALS | 0 | 等于给定值。 | +| CONTAINS | 1 | 包含给定值。 | +| STARTS_WITH | 2 | 以给定值开始。 | +| ENDS_WITH | 3 | 以给定值结束。 | + +## ResizeDirection9+ + +窗口调整大小的方向。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 说明 | +| ---------- | -------- | +| LEFT | 左方。 | +| RIGHT | 右方。 | +| UP | 上方。 | +| DOWN | 下方。 | +| LEFT_UP | 左上方。 | +| LEFT_DOWN | 左下方。 | +| RIGHT_UP | 右上方。 | +| RIGHT_DOWN | 右下方。 | + +## Point9+ + +坐标点信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ---- | -------- | ---- | ---- | ---------------- | +| X | number | 是 | 否 | 坐标点的横坐标。 | +| Y | number | 是 | 否 | 坐标点的纵坐标。 | + +## Rect9+ + +控件的边框信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 可读 | 可写 | 描述 | +| ------- | -------- | ---- | ---- | ------------------------- | +| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | +| topY | number | 是 | 否 | 控件边框的左上角的Y坐标。 | +| rightX | number | 是 | 否 | 控件边框的右下角的X坐标。 | +| bottomY | number | 是 | 否 | 控件边框的右下角的Y坐标。 | + +## WindowMode9+ + +**系统能力**:SystemCapability.Test.UiTest + +窗口的窗口模式。 + +| 名称 | 说明 | +| ---------- | ---------- | +| FULLSCREEN | 全屏模式。 | +| PRIMARY | 主窗口。 | +| SECONDARY | 第二窗口。 | +| FLOATING | 浮动窗口。 | + +## DisplayRotation9+ + +**系统能力**:SystemCapability.Test.UiTest + +设备显示器的显示方向。 + +| 名称 | 说明 | +| ------------ | ---------------------------------------- | +| ROTATION_0 | 设备显示器不旋转,初始形态垂直显示。 | +| ROTATION_90 | 设备显示器顺时针旋转90°,水平显示。 | +| ROTATION_180 | 设备显示器顺时针旋转180°,逆向垂直显示。 | +| ROTATION_270 | 设备显示器顺时针旋转270°,逆向水平显示。 | + +## WindowFilter9+ + +窗口的标志属性信息。 + +**系统能力**:SystemCapability.Test.UiTest + +| 名称 | 参数类型 | 必填 | 可读 | 可写 | 描述 | +| ---------- | -------- | ---- | ---- | ---- | -------------------------- | +| bundleName | string | 否 | 是 | 否 | 窗口归属应用的包名。 | +| title | string | 否 | 是 | 否 | 窗口的标题信息。 | +| focused | boolean | 否 | 是 | 否 | 窗口是否处于获焦状态。 | +| actived | boolean | 否 | 是 | 否 | 窗口是否正与用户进行交互。 | + ## On9+ UiTest框架在API9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
@@ -597,15 +690,15 @@ async function demo() { getBoundsCenter(): Promise\ -获取控件对象的中心点信息。 +获取控件对象所占区域的中心点信息。 **系统能力**:SystemCapability.Test.UiTest **返回值:** -| 类型 | 说明 | -| -------------------------- | --------------------------------------- | -| Promise\<[Point](#point9)> | 以Promise形式返回控件对象的中心点信息。 | +| 类型 | 说明 | +| -------------------------- | ----------------------------------------------- | +| Promise\<[Point](#point9)> | 以Promise形式返回控件对象所占区域的中心点信息。 | **错误码:** @@ -630,7 +723,7 @@ async function demo() { isClickable(): Promise\ -获取控件对象可点击状态。 +获取控件对象可点击属性。 **系统能力**:SystemCapability.Test.UiTest @@ -638,7 +731,7 @@ isClickable(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回控件对象可点击状态,true:可点击,false:不可点击。 | +| Promise\ | 以Promise形式返回控件对象是否可点击,true:可点击,false:不可点击。 | **错误码:** @@ -668,7 +761,7 @@ async function demo() { isLongClickable(): Promise\ -获取控件对象可长按点击状态。 +获取控件对象可长按点击属性。 **系统能力**:SystemCapability.Test.UiTest @@ -676,7 +769,7 @@ isLongClickable(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回控件对象能否长按点击状态,true:可长按点击,false:不可长按点击。 | +| Promise\ | 以Promise形式返回控件对象是否可安装点击,true:可长按点击,false:不可长按点击。 | **错误码:** @@ -744,7 +837,7 @@ async function demo() { isCheckable(): Promise\ -获取控件对象能否被勾选的属性。 +获取控件对象能否被勾选属性。 **系统能力**:SystemCapability.Test.UiTest @@ -752,7 +845,7 @@ isCheckable(): Promise\ | 错误码ID | 错误码信息 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回控件对象能否被勾选的属性,true:可被勾选,false:不可被勾选。 | +| Promise\ | 以Promise形式返回控件对象能否可被勾选属性,true:可被勾选,false:不可被勾选。 | **错误码:** @@ -782,7 +875,7 @@ async function demo() { isScrollable(): Promise\ -获取控件对象可滑动状态。 +获取控件对象可滑动属性。 **系统能力**:SystemCapability.Test.UiTest @@ -790,7 +883,7 @@ isScrollable(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回控件对象可滑动状态,true:可滑动,false:不可滑动。 | +| Promise\ | 以Promise形式返回控件对象是否可滑动,true:可滑动,false:不可滑动。 | **错误码:** @@ -860,7 +953,7 @@ async function demo() { isFocused(): Promise\ -判断控件对象是否获焦。 +判断控件对象获焦状态。 **系统能力**:SystemCapability.Test.UiTest @@ -868,7 +961,7 @@ isFocused(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回控件对象是否获焦,true:获焦,false:未获焦。 | +| Promise\ | 以Promise形式返回控件对象获焦状态,true:获焦,false:未获焦。 | **错误码:** @@ -904,9 +997,9 @@ isSelected(): Promise\ **返回值:** -| 类型 | 说明 | -| ----------------- | ----------------------------------------------------- | -| Promise\ | 控件对象被选中的状态,true:被选中,false:未被选中。 | +| 类型 | 说明 | +| ----------------- | --------------------------------------------------- | +| Promise\ | 控件对象被选中状态,true:被选中,false:未被选中。 | **错误码:** @@ -942,9 +1035,9 @@ inputText(text: string): Promise\ **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------- | -| text | string | 是 | 输入的文本信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------------------- | +| text | string | 是 | 输入的文本信息,当前支持英文和特殊字符。 | **错误码:** @@ -994,7 +1087,7 @@ async function demo() { scrollSearch(on: ON): Promise\ -在控件上滑动查找目标控件(适用于List等支持滑动的控件)。 +在控件上滑动查找目标控件(适用支持滑动的控件)。 **系统能力**:SystemCapability.Test.UiTest @@ -1033,7 +1126,7 @@ async function demo() { scrollToTop(speed?: number): Promise\ -在控件上滑动到顶部(适用于List等支持滑动的控件)。 +在控件上滑动到顶部(适用支持滑动的控件)。 **系统能力**:SystemCapability.Test.UiTest @@ -1066,7 +1159,7 @@ async function demo() { scrollToBottom(speed?: number): Promise\ -在控件上滑动到底部(适用于List等支持滑动的控件)。 +在控件上滑动到底部(适用支持滑动的控件)。 **系统能力**:SystemCapability.Test.UiTest @@ -1197,8 +1290,8 @@ async function demo() { ## Driver9+ -UiTest框架在API9中,Driver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 -该类提供的方法除Driver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 +Driver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能力。 +该类提供的方法除Driver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await方式调用。 ### create9+ @@ -1414,7 +1507,7 @@ async function demo() { assertComponentExist(on: On): Promise\ -断言API,用于断言当前界面存在满足给出的目标控件属性的控件。 +断言API,用于断言当前界面是否存在满足给出的目标属性的控件。 **系统能力**:SystemCapability.Test.UiTest @@ -1471,7 +1564,7 @@ async function demo() { triggerKey(keyCode: number): Promise\ -Driver对象采取如下操作:通过key值找到对应键并点击。 +Driver对象采取如下操作:传入key值实现模拟点击对应按键的效果。 **系统能力**:SystemCapability.Test.UiTest @@ -1502,7 +1595,7 @@ async function demo() { triggerCombineKeys(key0: number, key1: number, key2?: number): Promise\ -Driver对象通过给定的key值,找到对应组合键并点击。例如,Key值为(2072, 2019)时,Driver对象找到组合键并点击ctrl+c。 +Driver对象通过给定的key值,找到对应组合键并点击。例如,Key值为(2072, 2019)时,Driver对象找到key值对应的组合键并点击,如ctrl+c。 **系统能力**:SystemCapability.Test.UiTest @@ -1600,7 +1693,7 @@ async function demo() { longClick(x: number, y: number): Promise\ -Driver对象采取如下操作:在目标坐标点长按下。 +Driver对象采取如下操作:在目标坐标点长按。 **系统能力**:SystemCapability.Test.UiTest @@ -1632,7 +1725,7 @@ async function demo() { swipe(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ -Driver对象采取如下操作:从给出的起始坐标点滑向给出的目的坐标点。 +Driver对象采取如下操作:从起始坐标点滑向目的坐标点。 **系统能力**:SystemCapability.Test.UiTest @@ -1667,7 +1760,7 @@ async function demo() { drag(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ -Driver对象采取如下操作:从给出的起始坐标点拖拽至给出的目的坐标点。 +Driver对象采取如下操作:从起始坐标点拖拽至目的坐标点。 **系统能力**:SystemCapability.Test.UiTest @@ -1863,15 +1956,15 @@ async function demo() { getDisplayDensity(): Promise\ -获取当前设备的屏幕的分辨率。 +获取当前设备屏幕的分辨率。 **系统能力**:SystemCapability.Test.UiTest **返回值:** -| 类型 | 说明 | -| -------------------------- | ------------------------------------------- | -| Promise\<[Point](#point9)> | 以Promise的形式返回当前设备的屏幕的分辨率。 | +| 类型 | 说明 | +| -------------------------- | ----------------------------------------- | +| Promise\<[Point](#point9)> | 以Promise的形式返回当前设备屏幕的分辨率。 | **错误码:** @@ -1894,7 +1987,7 @@ async function demo() { wakeUpDisplay(): Promise\ -唤醒当前设备的屏幕。 +唤醒当前设备即设备亮屏。 **系统能力**:SystemCapability.Test.UiTest @@ -2024,14 +2117,14 @@ injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\ | 以Promise的形式返回植入操作是否成功完成。 | +| 类型 | 说明 | +| ----------------- | ------------------------------------- | +| Promise\ | 以Promise的形式返回操作是否成功完成。 | **错误码:** @@ -2058,7 +2151,7 @@ async function demo() { ## PointerMatrix9+ -表示存储多指操作中每根手指每一步动作的坐标点及其行为的二维数组。 +存储多指操作中每根手指每一步动作的坐标点及其行为的二维数组。 ### create9+ @@ -2121,22 +2214,22 @@ async function demo() { ## UiWindow9+ -UiTest中,UiWindow类代表了UI界面上的一个窗口,提供窗口属性获取,窗口拖动、调整窗口大小等API。 -该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 +UiWindow代表了UI界面上的一个窗口,提供窗口属性获取,窗口拖动、调整窗口大小等能力。 +该类提供的所有方法都使用Promise方式作为异步方法,需使用await方式调用。 ### getBundleName9+ getBundleName(): Promise\ -获取窗口的包名信息。 +获取窗口归属应用的包名信息。 **系统能力**:SystemCapability.Test.UiTest **返回值:** -| 类型 | 说明 | -| ---------------- | --------------------------------- | -| Promise\ | 以Promise形式返回窗口的包名信息。 | +| 类型 | 说明 | +| ---------------- | ----------------------------------------- | +| Promise\ | 以Promise形式返回窗口归属应用的包名信息。 | **错误码:** @@ -2260,7 +2353,7 @@ async function demo() { isFocused(): Promise\ -判断窗口是否获焦。 +判断窗口是否处于获焦状态。 **系统能力**:SystemCapability.Test.UiTest @@ -2268,7 +2361,7 @@ isFocused(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回窗口对象是否获焦,true:获焦,false:未获焦。 | +| Promise\ | 以Promise形式返回窗口对象是否获取获焦状态,true:获焦,false:未获焦。 | **错误码:** @@ -2293,7 +2386,7 @@ async function demo() { isActived(): Promise\ -判断窗口是否为用户交互窗口。 +判断窗口是否为用户正在交互窗口。 **系统能力**:SystemCapability.Test.UiTest @@ -2301,7 +2394,7 @@ isActived(): Promise\ | 类型 | 说明 | | ----------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回窗口对象是否为用户交互窗口,true:交互窗口,false:非交互窗口。 | +| Promise\ | 以Promise形式返回窗口对象是否为用户正在交互窗口,true:交互窗口,false:非交互窗口。 | **错误码:** @@ -2388,7 +2481,7 @@ async function demo() { resize(wide: number, height: number, direction: ResizeDirection): Promise\ -根据传入的宽、高和调整方向来调整窗口的大小。适用于支持大小调整的窗口。 +根据传入的宽、高和调整方向来调整窗口的大小。适用于支持调整大小的窗口。 **系统能力**:SystemCapability.Test.UiTest @@ -2424,7 +2517,7 @@ async function demo() { split(): Promise\ -将窗口模式切换成分屏模式。适用于支持切屏操作的窗口。 +将窗口模式切换成分屏模式。适用于支持切换分屏模式的窗口。 **系统能力**:SystemCapability.Test.UiTest @@ -2560,99 +2653,6 @@ async function demo() { } ``` -## MatchPattern - -控件属性支持的匹配模式。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 值 | 说明 | -| ----------- | ---- | -------------- | -| EQUALS | 0 | 等于给定值。 | -| CONTAINS | 1 | 包含给定值。 | -| STARTS_WITH | 2 | 从给定值开始。 | -| ENDS_WITH | 3 | 以给定值结束。 | - -## ResizeDirection9+ - -窗口调整大小的方向。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 说明 | -| ---------- | -------- | -| LEFT | 左方。 | -| RIGHT | 右方。 | -| UP | 上方。 | -| DOWN | 下方。 | -| LEFT_UP | 左上方。 | -| LEFT_DOWN | 左下方。 | -| RIGHT_UP | 右上方。 | -| RIGHT_DOWN | 右下方。 | - -## Point9+ - -坐标点信息。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ---- | -------- | ---- | ---- | ---------------- | -| X | number | 是 | 否 | 坐标点的横坐标。 | -| Y | number | 是 | 否 | 坐标点的纵坐标。 | - -## Rect9+ - -控件的边框信息。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 参数类型 | 可读 | 可写 | 描述 | -| ------- | -------- | ---- | ---- | ------------------------- | -| leftX | number | 是 | 否 | 控件边框的左上角的X坐标。 | -| topY | number | 是 | 否 | 控件边框的左上角的Y坐标。 | -| rightX | number | 是 | 否 | 控件边框的右下角的X坐标。 | -| bottomY | number | 是 | 否 | 控件边框的右下角的Y坐标。 | - -## WindowMode9+ - -**系统能力**:SystemCapability.Test.UiTest - -窗口的窗口模式。 - -| 名称 | 说明 | -| ---------- | ---------- | -| FULLSCREEN | 全屏模式。 | -| PRIMARY | 主窗口。 | -| SECONDARY | 第二窗口。 | -| FLOATING | 浮动窗口。 | - -## DisplayRotation9+ - -**系统能力**:SystemCapability.Test.UiTest - -设备显示器的显示方向。 - -| 名称 | 说明 | -| ------------ | ---------------------------------------- | -| ROTATION_0 | 设备显示器不旋转,初始形态垂直显示。 | -| ROTATION_90 | 设备显示器顺时针旋转90°,水平显示。 | -| ROTATION_180 | 设备显示器顺时针旋转180°,逆向垂直显示。 | -| ROTATION_270 | 设备显示器顺时针旋转270°,逆向水平显示。 | - -## WindowFilter9+ - -窗口的标志属性信息。 - -**系统能力**:SystemCapability.Test.UiTest - -| 名称 | 参数类型 | 必填 | 可读 | 可写 | 描述 | -| ---------- | -------- | ---- | ---- | ---- | -------------------------- | -| bundleName | string | 否 | 是 | 否 | 窗口对应的包名。 | -| title | string | 否 | 是 | 否 | 窗口的标题。 | -| focused | boolean | 否 | 是 | 否 | 窗口是否获焦。 | -| actived | boolean | 否 | 是 | 否 | 窗口是否正与用户进行交互。 | - ## By(deprecated) UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
@@ -2729,7 +2729,7 @@ id(id: number): By 指定目标控件id属性,返回By对象自身。 -从API version9开始不再维护,被废弃。 +从API version9开始废弃。 **系统能力**:SystemCapability.Test.UiTest @@ -3051,7 +3051,7 @@ getId(): Promise\ 获取控件对象的id值。 -从API version9开始不再维护,建议使用[getId9+](#getid9)。 +从API version9开始不再维护,被废弃。 **系统能力**:SystemCapability.Test.UiTest @@ -3077,7 +3077,7 @@ getKey(): Promise\ 获取控件对象的key值。 -从API version9开始不再维护,被废弃。 +从API version9开始不再维护,建议使用[getId9+](#getid9) **系统能力**:SystemCapability.Test.UiTest diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md index d03a2a041999f38c12d8dad5d2cd1f70e8656a7d..db1c26ddd171304b7301159c4881e229fdd1826c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md @@ -18,7 +18,7 @@ Refresh\(value: \{ refreshing: boolean, offset?: number | string , fr | 参数 | 参数名 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| refreshing | boolean | 是 | 当前组件是否正在刷新。
该参数支持[$$](../../ui/ts-syntactic-sugar.md)双向绑定变量。 | +| refreshing | boolean | 是 | 当前组件是否正在刷新。
该参数支持[$$](../../quick-start/arkts-restrictions-and-extensions.md#变量的双向绑定)双向绑定变量。 | | offset | string \| number | 否 | 刷新组件静止时距离父组件顶部的距离。
默认值:16,单位vp | | friction | number \| string | 否 | 下拉摩擦系数,取值范围为0到100。
默认值:62
- 0表示下拉刷新容器不跟随手势下拉而下拉。
- 100表示下拉刷新容器紧紧跟随手势下拉而下拉。
- 数值越大,下拉刷新容器跟随手势下拉的反应越灵敏。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index cc257b0dcb26a633ee9116a19c972ac9608a5d34..69dce85187ccc50c4f54e253fe9ce85b5c4fcf77 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -18,7 +18,7 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------------------- | ---------------------------------------- | ------------------------- | ---------------------- | -| builder | [CustomDialog](../../ui/ts-component-based-customdialog.md) | 是 | 自定义弹窗内容构造器。 | +| builder | [CustomDialog](../../quick-start/arkts-dynamic-ui-elememt-building.md#customdialog) | 是 | 自定义弹窗内容构造器。 | | cancel | () => void | 否 | 点击遮障层退出时的回调。 | | autoCancel | boolean | 否 | 是否允许点击遮障层退出。
默认值:true | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。
默认值:DialogAlignment.Default | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-types.md b/zh-cn/application-dev/reference/arkui-ts/ts-types.md index 7909514b3e300b9aac38e4b370ebccf9519df4ae..a55b163537c12541dd54949a685f317c02ea83a8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-types.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-types.md @@ -213,5 +213,5 @@ | 名称 | 类型定义 | 描述 | | ------------- | ---------------------- | ---------------------------------------- | -| CustomBuilder | () => any | 该方法类型必须使用@Builder装饰器修饰。具体用法见[@Builder](../../ui/ts-component-based-builder.md)。 | +| CustomBuilder | () => any | 该方法类型必须使用@Builder装饰器修饰。具体用法见[@Builder](../../quick-start/arkts-dynamic-ui-elememt-building.md#builder)。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md index 7d90b701c6991739de6f2c745e356a7f6ca3c516..acb3efd2c503f4f5cc370d2e53c651103b38add4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md @@ -10,7 +10,7 @@ | 名称 | 参数类型 | 描述 | | ---------- | ---------------------------- | ------------------------------------------ | -| visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../ui/ts-rending-control-syntax-if-else.md)代替。
默认值:Visibility.Visible| +| visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../quick-start/arkts-rendering-control.md#条件渲染)代替。
默认值:Visibility.Visible| ## 示例 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md b/zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md new file mode 100644 index 0000000000000000000000000000000000000000..e8674f395457d04a6f8f53f5933be94a9082ae5d --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md @@ -0,0 +1,96 @@ +# 无障碍子系统错误码 + +## 9300001 输入无效的包名称或者Ability名称 + +**错误信息** + +Invalid bundle name or ability name. + +**错误描述** + +当输入的包名称或者Ability名称无效时,方法将返回该错误码。 + +**可能原因** + +该错误码表示输入无效的包名称或者Ability名称,可能原因如下: +1. 包名称不存在。 +2. 包里面没有对应的Ability。 + +**处理步骤** + +1. 检查包名称是否正确。 +2. 检查包名对应的Ability是否正确。 + +## 9300002 目标Ability已启用 + +**错误信息** + +Target ability already enabled. + +**错误描述** + +当目标Ability已启用时,方法将返回该错误码。 + +**可能原因** + +该错误码表示目标Ability已启用,可能原因是目标Ability已经启用,无法再次启用。 + +**处理步骤** + +1. 停止该目标Ability。 +2. 重新启用该目标Ability。 + +## 9300003 不具备执行该操作的无障碍权限 + +**错误信息** + +Do not have accessibility right for this operation. + +**错误描述** + +当应用执行了用户在启用无障碍扩展应用时没有开启的辅助操作时,方法将返回该错误码。 + +**可能原因** + +该错误码表示应用不具备该操作的无障碍权限,可能原因是应用执行了用户在启用无障碍扩展应用时没有开启的辅助操作。 + +**处理步骤** + +1. 尝试向用户提示请求执行无障碍辅助操作的必要性,并获取用户授权。 +2. 重新启用无障碍扩展应用,并开启所需的辅助操作。 + +## 9300004 属性不存在 + +**错误信息** + +This property does not exist. + +**错误描述** + +当输入无障碍节点元素中不存在的属性时,方法将返回该错误码。 + +**可能原因** + +该错误码表示输入了无效的无障碍节点元素的属性,可能原因是无障碍节点元素中不存在该属性。 + +**处理步骤** + +检查无障碍节点元素中是否存在该属性。 + +## 9300005 不支持该操作 + +**错误信息** + +This action is not supported. + +**错误描述** + +当应用执行无障碍节点元素不支持的操作时,方法将返回该错误码。 + +**可能原因** + +该错误码表示执行了无障碍节点元素不支持的操作,可能原因是无障碍节点元素不支持执行该操作。 + +**处理步骤** + +确认该无障碍节点元素支持的操作列表中是否包含该操作。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-batteryStatistics.md b/zh-cn/application-dev/reference/errorcodes/errorcode-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..5787950b7a841ffdefa230e42493180dcc68f29f --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-batteryStatistics.md @@ -0,0 +1,29 @@ +# 耗电统计错误码 + +## 4600101 连接服务失败 + +**错误信息** + +Operation failed. Cannot connect to service. + +**错误描述** + +操作失败,连接系统服务发生异常。 + +**可能原因** + +1. 系统服务停止运行。 + +2. 系统服务内部通讯发生异常。 + +**处理步骤** + +检查系统服务是否正常运行。 + +1. 在控制台中输入如下命令,查看当前的系统服务列表。 + + ```bash + > hdc shell hidumper -ls + ``` + +2. 查看系统服务列表中是否包含BatteryStatisticsService系统服务。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-brightness.md b/zh-cn/application-dev/reference/errorcodes/errorcode-brightness.md new file mode 100644 index 0000000000000000000000000000000000000000..b5d83d90fde5bdf977f6afb76f41d1bed9bab4ed --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-brightness.md @@ -0,0 +1,29 @@ +# 屏幕亮度错误码 + +## 4700101 连接服务失败 + +**错误信息** + +Operation failed. Cannot connect to service. + +**错误描述** + +操作失败,连接系统服务发生异常。 + +**可能原因** + +1. 系统服务停止运行。 + +2. 系统服务内部通讯发生异常。 + +**处理步骤** + +检查系统服务是否正常运行。 + +1. 在控制台中输入如下命令,查看当前的系统服务列表。 + + ```bash + > hdc shell hidumper -ls + ``` + +2. 查看系统服务列表中是否包含DisplayPowerManagerService系统服务。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-power.md b/zh-cn/application-dev/reference/errorcodes/errorcode-power.md new file mode 100644 index 0000000000000000000000000000000000000000..235c30c55270902327d319a843c21d7ea250d0a1 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-power.md @@ -0,0 +1,47 @@ +# 系统电源管理错误码 + +## 4900101 连接服务失败 + +**错误信息** + +Operation failed. Cannot connect to service. + +**错误描述** + +操作失败,连接系统服务发生异常。 + +**可能原因** + +1. 系统服务停止运行。 + +2. 系统服务内部通讯发生异常。 + +**处理步骤** + +检查系统服务是否正常运行。 + +1. 在控制台中输入如下命令,查看当前的系统服务列表。 + + ```bash + > hdc shell hidumper -ls + ``` + +2. 查看系统服务列表中是否包含PowerManagerService系统服务。 + +## 4900102 正在关机中 + +**错误信息** + +Operation failed. System is shutting down. + +**错误描述** + +操作失败,系统正在关机。 + +**可能原因** + +系统正在处于关机过程中。 + +**处理步骤** + +在系统正常运行的状态下进行操作。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-runninglock.md b/zh-cn/application-dev/reference/errorcodes/errorcode-runninglock.md new file mode 100644 index 0000000000000000000000000000000000000000..e346d88ec7d26c3d25e0b935ce1d1007b659cd78 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-runninglock.md @@ -0,0 +1,29 @@ +# RunningLock锁错误码 + +## 4900101 连接服务失败 + +**错误信息** + +Operation failed. Cannot connect to service. + +**错误描述** + +操作失败,连接系统服务发生异常。 + +**可能原因** + +1. 系统服务停止运行。 + +2. 系统服务内部通讯发生异常。 + +**处理步骤** + +检查系统服务是否正常运行。 + +1. 在控制台中输入如下命令,查看当前的系统服务列表。 + + ```bash + > hdc shell hidumper -ls + ``` + +2. 查看系统服务列表中是否包含PowerManagerService系统服务。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-thermal.md b/zh-cn/application-dev/reference/errorcodes/errorcode-thermal.md new file mode 100644 index 0000000000000000000000000000000000000000..e5665089092a315655ceb517e275147af89776b6 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-thermal.md @@ -0,0 +1,29 @@ +# 热管理错误码 + +## 4800101 连接服务失败 + +**错误信息** + +Operation failed. Cannot connect to service. + +**错误描述** + +操作失败,连接系统服务发生异常。 + +**可能原因** + +1. 系统服务停止运行。 + +2. 系统服务内部通讯发生异常。 + +**处理步骤** + +检查系统服务是否正常运行。 + +1. 在控制台中输入如下命令,查看当前的系统服务列表。 + + ```bash + > hdc shell hidumper -ls + ``` + +2. 查看系统服务列表中是否包含ThermalService系统服务。 diff --git a/zh-cn/application-dev/ui/ui-ts-components.md b/zh-cn/application-dev/ui/ui-ts-components.md index 45d22d02d3255dddcd90760c911595a942c2ee17..775cb434d336028df04109f4a1eda38a1d007923 100644 --- a/zh-cn/application-dev/ui/ui-ts-components.md +++ b/zh-cn/application-dev/ui/ui-ts-components.md @@ -5,7 +5,7 @@ ## 组件和装饰器 -在声明式UI中,所有的页面都是由组件构成。组件的数据结构为struct,装饰器[@Component](../ui/ts-component-based-component.md)是组件化的标志。用@Component修饰的struct表示这个结构体有了组件化的能力。 +在声明式UI中,所有的页面都是由组件构成。组件的数据结构为struct,装饰器@Component是组件化的标志。用@Component修饰的struct表示这个结构体有了组件化的能力。 自定义组件的声明方式为: @@ -22,7 +22,7 @@ interface Builder { } ``` -[@Entry](../ui/ts-component-based-entry.md)修饰的Component表示该Component是页面的总入口,也可以理解为页面的根节点。值得注意的是,一个页面有且仅能有一个@Entry,只有被@Entry修饰的组件或者其子组件,才会在页面上显示。 +@Entry修饰的Component表示该Component是页面的总入口,也可以理解为页面的根节点。值得注意的是,一个页面有且仅能有一个@Entry,只有被@Entry修饰的组件或者其子组件,才会在页面上显示。 @Component和@Entry都是基础且十分重要的装饰器。简单地理解,装饰器就是某一种修饰,给被装饰的对象赋予某一种能力,比如@Entry就是页面入口的能力,@Component就是组件化能力。 diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png new file mode 100644 index 0000000000000000000000000000000000000000..248ea1854492ca3d2c02fb5a1be1fd5d4ef408a8 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-audio-03.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png new file mode 100644 index 0000000000000000000000000000000000000000..6be451aec844699dc7d254de5c48ce08507a8431 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png new file mode 100644 index 0000000000000000000000000000000000000000..062598d4095dbbd7b41c460aa1b09634a3bcb1b2 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-backlight-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png new file mode 100644 index 0000000000000000000000000000000000000000..2bf182464e58219294cb38f36ed652c6391ff2a8 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-bt-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png new file mode 100644 index 0000000000000000000000000000000000000000..1a4fa27e98e5bb4568be1399b57da3b987ee4fbf Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-camera-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png new file mode 100644 index 0000000000000000000000000000000000000000..3fae6a7aa94e445668e0dd80a1374a04e607f24e Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-sensor-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png new file mode 100644 index 0000000000000000000000000000000000000000..83884ab97b8cf678c466da4d1cd71b116d1199a1 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png new file mode 100644 index 0000000000000000000000000000000000000000..a9d5ec775f67a0775c38532455d91f3a5b616e58 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-tp-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png new file mode 100644 index 0000000000000000000000000000000000000000..5527ef2a4b3887eb51a9c9e340a107da5535a425 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-vibrator-01.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png new file mode 100644 index 0000000000000000000000000000000000000000..d150f2aa9c744fdf9ce144ce614be99c88587059 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-02.png differ diff --git a/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png new file mode 100644 index 0000000000000000000000000000000000000000..24f64af806b6e0f5acb1006a22966bd79d3a8a49 Binary files /dev/null and b/zh-cn/device-dev/porting/figures/dayu200/dayu200-wifi-03.png differ diff --git a/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md b/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md index 525055339c5e23b7d5d1290ca13a1a0893520ed1..49a9a80a4852e2975095672f55e898fb2ba0ca8b 100755 --- a/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md +++ b/zh-cn/device-dev/porting/porting-dayu200-on_standard-demo.md @@ -1,6 +1,6 @@ -**标准系统方案之瑞芯微RK3568移植案例** +# 标准系统方案之瑞芯微RK3568移植案例 -​ 本文章是基于瑞芯微RK3568芯片的DAYU200开发板,进行标准系统相关功能的移植,主要包括产品配置添加,内核启动、升级,音频ADM化,Camera,TP,LCD,WIFI,BT,vibrator、sensor、图形显示模块的适配案例总结,以及相关功能的适配。 +​本文章是基于瑞芯微RK3568芯片的DAYU200开发板,进行标准系统相关功能的移植,主要包括产品配置添加,内核启动、升级,音频ADM化,Camera,TP,LCD,WIFI,BT,vibrator、sensor、图形显示模块的适配案例总结,以及相关功能的适配。 ## 产品配置和目录规划 @@ -212,7 +212,7 @@ init相关配置请参考[启动子系统的规范要求](https://gitee.com/open ADM结构框图如下,Audio Peripheral Drivers和Platform Drivers为平台适配需要完成的工作。 -dayu200-audio-03.png +![dayu200-audio-03.png](figures/dayu200/dayu200-audio-03.png) 结合第1步梳理出来的Audio结构分析,Audio Peripheral Drivers包含Rk809的驱动,Platform Drivers包含DMA驱动和I2S驱动。 @@ -1085,7 +1085,7 @@ product.gni中指定了chipset_build_deps camera_device_manager_deps 和 camera_ #### 框架适配介绍 -​ img + ![dayu200-camera-01.png](figures/dayu200/dayu200-camera-01.png) ​ 以V4l2为例,pipeline的连接方式是在HCS配置文件中配置连接,数据源我们称之为SourceNode,主要包括硬件设备的控制、数据流的轮转等。 @@ -1883,7 +1883,8 @@ struct v4l2_buffer { - InputController:提供input设备的业务控制接口,包括获取器件信息及设备类型、设置电源状态等。 **图 1** INPUT模块HDI接口层框架图 -dayu200-tp-01.png + +![dayu200-tp-01.png](figures/dayu200/dayu200-tp-01.png) 相关目录下源代码目录结构如下所示 @@ -1922,7 +1923,7 @@ tp驱动的适配依赖hdf的input模型,hdf的input模型提供了TP,KEY, 从功能的角度看hdf input模块的框架如下: -tp +![dayu200-tp-02.png](figures/dayu200/dayu200-tp-02.png) 因为hdf input模型的高度抽象集成,TP驱动的适配驱动主要涉及器件驱动层的适配。 @@ -2294,7 +2295,7 @@ device4 :: deviceNode { 基于HDF框架开发的 背光驱动模型 - +![dayu200-backlight-01.png](figures/dayu200/dayu200-backlight-01.png) rk3568背光是通过pwm控制占空比实现的,具体使用的是pwm4 @@ -2398,7 +2399,7 @@ static struct BacklightOps g_blDevOps = { 其实使用的就是HDF PWM 实现的对接内核pwm的接口 - +![dayu200-backlight-02.png](figures/dayu200/dayu200-backlight-02.png) 在LCD HDF器件驱动注册背光 @@ -2493,7 +2494,7 @@ HDF WiFi框架总体框架图 #### 驱动模块初始化流程分析 -dayu200-wifi-02.png +![dayu200-wifi-02.png](figures/dayu200/dayu200-wifi-02.png) Ap6275s 是一款SDIO设备WiFi模组驱动,使用标准Linux的SDIO设备驱动。内核模块初始化入口module_init()调用dhd_wifi_platform_load_sdio()函数进行初始化工作,这里调用wifi_platform_set_power()进行GPIO上电,调用dhd_wlan_set_carddetect()进行探测SDIO设备卡,最后调用sdio_register_driver(&bcmsdh_sdmmc_driver);进行SDIO设备驱动的注册,SDIO总线已经检测到WiFi模块设备 根据设备号和厂商号与该设备驱动匹配, 所以立即回调该驱动的bcmsdh_sdmmc_probe()函数,这里进行WiFi模组芯片的初始化工作,最后创建net_device网络接口wlan0,然后注册到Linux内核协议栈中。 @@ -2557,7 +2558,7 @@ HDF WLAN驱动框架由Module、NetDevice、NetBuf、BUS、HAL、Client 和 Mess 代码流程框图如下: -dayu200-wifi-03.png +![dayu200-wifi-03.png](figures/dayu200/dayu200-wifi-03.png) 代码位于device/hihope/rk3568/wifi/bcmdhd_wifi6/hdf_driver_bdh_register.c @@ -2801,7 +2802,7 @@ p2p-p2p0-0 Link encap:Ethernet HWaddr 12:2c:6b:11:21:e0 Driver bcmsdh_sdmmc 蓝牙整体硬件架构上分为主机(计算机或MCU)和主机控制器(实际蓝牙芯片组)两部分;主机和控制器之间的通信遵循主机控制器接口(HCI),如下所示: - +![dayu200-bt-01.png](figures/dayu200/dayu200-bt-01.png) HCI定义了如何交换命令,事件,异步和同步数据包。异步数据包(ACL)用于数据传输,而同步数据包(SCO)用于带有耳机和免提配置文件的语音。 @@ -3148,7 +3149,7 @@ void hw_process_event(HC_BT_HDR *p_buf) 基于HDF(Hardware Driver Foundation)驱动框架开发的Sensor驱动模型 - +![dayu200-sensor-01.png](figures/dayu200/dayu200-sensor-01.png) rk3568 支持accel sensor,整体的驱动框架openharmony 主线已经具备,只需要实现具体的器件驱动即可。 @@ -3383,7 +3384,7 @@ Vibrator驱动模型主要包含Vibrator(传感器)相关的HDI接口与实 **图 1** Vibrator驱动模型图 - +![dayu200-vibrator-01.png](figures/dayu200/dayu200-vibrator-01.png) rk3568 支持线性马达,整体的驱动框架openharmony 主线已经具备,只需要实现具体的器件驱动即可。 diff --git a/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md b/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md index aaf0a675de0ddd55139c87b5375c55be025e17b9..ee236e2a7d0303f436e419a23536a5d54faf5c92 100644 --- a/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md +++ b/zh-cn/device-dev/porting/porting-yangfan-on_standard-demo.md @@ -1551,7 +1551,8 @@ struct v4l2_buffer { - InputController:提供input设备的业务控制接口,包括获取器件信息及设备类型、设置电源状态等。 **图 1** INPUT模块HDI接口层框架图 -dayu200-tp-01.png + +![dayu200-tp-01.png](figures/dayu200/dayu200-tp-01.png) 相关目录下源代码目录结构如下所示 diff --git a/zh-cn/readme/figures/build_framework_ZN.PNG b/zh-cn/readme/figures/build_framework_ZN.PNG deleted file mode 100644 index 03f4d6f6cffc9d3552f86f197230d01a50e2860e..0000000000000000000000000000000000000000 Binary files a/zh-cn/readme/figures/build_framework_ZN.PNG and /dev/null differ diff --git "a/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" index 60c32bac0ca677738ef065c6031bfc432d2c69e1..2856eb0a36a3206d34b12b6a422aaa1a737f832b 100755 --- "a/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\345\220\257\345\212\250\346\201\242\345\244\215\345\255\220\347\263\273\347\273\237.md" @@ -1,10 +1,5 @@ # 启动恢复子系统 -- [简介](#section11660541593) -- [目录](#section161941989596) -- [约束](#section1718733212019) -- [使用说明](#section8533192617117) -- [相关仓](#section1371113476307) ## 简介 @@ -14,7 +9,7 @@ 支持使用LiteOS-A和Linux内核的平台。 - 负责处理从内核加载第一个用户态进程开始,到第一个应用程序启动之间的系统服务进程启动过程。启动恢复子系统除负责加载各系统关键进程之外,还需在启动的同时设置其对应权限,并在子进程启动后对指定进程实行保活(若进程意外退出要重新启动),对于核心进程意外退出时,启动恢复子系统还要执行系统重启操作。详见“[init启动引导组件](../device-dev/subsystems/subsys-boot-init.md)”部分。 + 负责处理从内核加载第一个用户态进程开始,到第一个应用程序启动之间的系统服务进程启动过程。启动恢复子系统除负责加载各系统关键进程之外,还需在启动的同时设置其对应权限,并在子进程启动后对指定进程实行保活(若进程意外退出要重新启动),对于核心进程意外退出时,启动恢复子系统还要执行系统重启操作。详见“[init启动引导组件](../device-dev/subsystems/subsys-boot-init-cfg.md)”部分。 - appspawn应用孵化器组件 @@ -33,7 +28,7 @@ 负责提供获取与设置操作系统相关的系统属性。 - 支持全量系统平台。支持的系统属性包括:默认系统属性、OEM厂商系统属性和自定义系统属性。OEM厂商部分仅提供默认值,具体值需OEM产品方按需进行调整,详见“[syspara系统属性组件](../device-dev/subsystems/subsys-boot-syspara.md)”部分。 + 支持全量系统平台。支持的系统属性包括:默认系统属性、OEM厂商系统属性和自定义系统属性。OEM厂商部分仅提供默认值,具体值需OEM产品方按需进行调整,详见“[syspara系统属性组件](../device-dev/subsystems/subsys-boot-init-sysparam.md)”部分。 ## 目录