diff --git a/CODEOWNERS b/CODEOWNERS index 1e6d1e90ebe18fdf635aea24811acebd8a473d78..b2355ad1397df0b851c7d092315fb9c450cc9d46 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -177,9 +177,9 @@ zh-cn/application-dev/napi/napi-guidelines.md @RayShih zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease -zh-cn/application-dev/website.md @zengyawen zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @qinxiaowang +zh-cn/application-dev/application-test/ @HelloCrease zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @RayShih zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @RayShih @@ -225,7 +225,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @RayS zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @RayShih zh-cn/application-dev/reference/apis/js-apis-emitter.md @RayShih zh-cn/application-dev/reference/apis/js-apis-notification.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-eventhub.md @RayShih zh-cn/application-dev/reference/apis/js-apis-Bundle.md @RayShih zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @RayShih @@ -369,7 +369,6 @@ zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen -zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen zh-cn/application-dev/reference/apis/development-intro.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @RayShih @@ -445,3 +444,5 @@ zh-cn/application-dev/reference/apis/js-apis-net-policy.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-net-statistics.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-tlsSocket.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @zengyawen diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index 4abf217eee28052d3163d32aa0bce18893e1df08..d5cd52e64ed5064ded90efea7d60898e1c2ee96c 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -235,13 +235,13 @@ export default class MainAbility extends Ability { For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). -### Obtaining the Context on an eTS Page +### Obtaining the Context on an ArkTS Page -In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an eTS page. In some scenarios, you need to obtain the context on the page to call related APIs. +In the stage model, in the `onWindowStageCreate` lifecycle of an ability, you can call `SetUIContent` of `WindowStage` to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs. **How to Obtain** -Use the API described in the table below to obtain the context associated with an eTS page. +Use the API described in the table below to obtain the context associated with an ArkTS page. | API | Description | | :------------------------------------ | :--------------------------- | 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/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index f471f4a6eed7d3eb2c96dab8cae4cb7480a13616..188b4f1336e2c56562f594e42dc26cabf8a8fc55 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -17,11 +17,11 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .so Naming Rules -Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. +Each module has a .so file. For example, if the module name is `hello`, name the .so file `libhello.so`. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. ### JS Objects and Threads -The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. +The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. Observe the following rules: * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. @@ -640,8 +640,3 @@ export default { } } ``` -## Samples -The following samples are provided for native API development: -- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) -- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) -- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 2326ebb9436384c4476c2b834e9ea8c58533d1e7..e5e4ee0ea6213711aa17f1458385298f545d454e 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,8 +1,8 @@ # Development References - -- [Component Reference (TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) -- [Component Reference (JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md) -- [API Reference (JS and TS APIs)](apis/Readme-EN.md) -- API Reference (Native APIs) - - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) +- [SysCap List](syscap-list.md) +- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) +- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) +- [API Reference (JS and TS APIs)](apis/Readme-EN.md) +- API Reference (Native APIs) + - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index e580b6bbef7bd71869de1da19a3a3d5c4757370d..beab6e2411714274074d3e0cbdfb13cc60ba574b 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,9 +1,7 @@ # APIs - [API Reference Document Description](development-intro.md) - - Ability Framework - - FA Model - [@ohos.ability.featureAbility](js-apis-featureAbility.md) - [@ohos.ability.particleAbility](js-apis-particleAbility.md) @@ -28,8 +26,6 @@ - application/[FormExtensionContext](js-apis-formextensioncontext.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - - [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md) - - [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) - FA and Stage Models - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) @@ -60,18 +56,15 @@ - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) + - application/[ProcessRunningInformation](js-apis-processrunninginformation.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - continuation/[ContinuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification - - [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.events.emitter](js-apis-emitter.md) - [@ohos.notification](js-apis-notification.md) - - [@ohos.reminderAgent](js-apis-reminderAgent.md) - application/[EventHub](js-apis-eventhub.md) - -- Bundle Management - + - Bundle Management - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) @@ -92,17 +85,13 @@ - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[ShortcutInfo](js-apis-bundle-ShortcutInfo.md) + - bundle/[ShortcutInfo(deprecated)](js-apis-bundle-ShortcutInfo.md) - UI Page - - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - - [@ohos.prompt](js-apis-prompt.md) - [@ohos.router](js-apis-router.md) - [@ohos.uiAppearance](js-apis-uiappearance.md) - -- Graphics - + - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) @@ -111,42 +100,31 @@ - [@ohos.window](js-apis-window.md) - [webgl](js-apis-webgl.md) - [webgl2](js-apis-webgl2.md) - - Media - - [@ohos.multimedia.audio](js-apis-audio.md) - [@ohos.multimedia.camera](js-apis-camera.md) - [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.media](js-apis-media.md) - - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - - Resource Management - - [@ohos.i18n](js-apis-i18n.md) - [@ohos.intl](js-apis-intl.md) - [@ohos.resourceManager](js-apis-resource-manager.md) - -- Resource Scheduling - +- Resource Scheduling - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.distributedMissionManager](js-apis-distributedMissionManager.md) - [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - - Custom Management - - [@ohos.configPolicy](js-apis-config-policy.md) - - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - enterpriseDeviceManager/[DeviceSettingsManager](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md) - - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@system.cipher](js-apis-system-cipher.md) - Data Management @@ -167,46 +145,40 @@ - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.fileManager](js-apis-filemanager.md) + - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) + - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.volumeManager](js-apis-volumemanager.md) - - [@ohos.securityLabel](js-apis-securityLabel.md) - - Telephony Service - - [@ohos.contact](js-apis-contact.md) - [@ohos.telephony.call](js-apis-call.md) + - [@ohos.telephony.data](js-apis-telephony-data.md) - [@ohos.telephony.observer](js-apis-observer.md) - [@ohos.telephony.radio](js-apis-radio.md) - [@ohos.telephony.sim](js-apis-sim.md) - [@ohos.telephony.sms](js-apis-sms.md) - - [@ohos.telephony.data](js-apis-telephony-data.md) - - Network Management - - [@ohos.net.connection](js-apis-net-connection.md) - [@ohos.net.http](js-apis-http.md) - - [@ohos.request](js-apis-request.md) - [@ohos.net.socket](js-apis-socket.md) + - [@ohos.net.webSocket](js-apis-webSocket.md) - + - [@ohos.request](js-apis-request.md) - Connectivity - - [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.connectedTag](js-apis-connectedTag.md) - [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - - [@ohos.nfc.tag](js-apis-nfctech.md) - - [@ohos.nfc.tag](js-apis-tagSession.md) - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - + - [@ohos.nfc.tag](js-apis-nfctech.md) + - [@ohos.nfc.tag](js-apis-tagSession.md) - Basic Features - - [@ohos.accessibility](js-apis-accessibility.md) + - [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.hiAppEvent](js-apis-hiappevent.md) - [@ohos.hichecker](js-apis-hichecker.md) @@ -217,13 +189,15 @@ - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.inputMethod](js-apis-inputmethod.md) - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) + - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) - [Timer](js-apis-timer.md) - + - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) @@ -239,6 +213,7 @@ - [@ohos.multimodalInput.keyCode](js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) + - [@ohos.multimodalInput.pointer](js-apis-pointer.md) - [@ohos.multimodalInput.touchEvent](js-apis-touchevent.md) - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) @@ -249,15 +224,12 @@ - [@ohos.update](js-apis-update.md) - [@ohos.usb](js-apis-usb.md) - [@ohos.vibrator](js-apis-vibrator.md) - -- Account Management - +- Account Management - [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.osAccount](js-apis-osAccount.md) - -- Language Base Class Library - + - Language Base Class Library + - [@ohos.buffer](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) @@ -279,16 +251,14 @@ - [@ohos.util.Vector](js-apis-vector.md) - [@ohos.worker](js-apis-worker.md) - [@ohos.xml](js-apis-xml.md) - - Test - - [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) - -- APIs No Longer Maintained - +- APIs No Longer Maintained - [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.data.storage](js-apis-data-storage.md) + - [@ohos.prompt](js-apis-prompt.md) + - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) - [@system.bluetooth](js-apis-system-bluetooth.md) 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-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md deleted file mode 100644 index b80660185cffaf10993bf9c54ba1f88a1f16b7f4..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ /dev/null @@ -1,282 +0,0 @@ -# User File Access and Management - -The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. - ->**NOTE**
-> ->- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. - -## Modules to Import - -```js -import filemanager from '@ohos.fileManager'; -``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - -Obtains information about the root album or directory in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| - -**Example** - - ```js - filemanager.getRoot().then((fileInfos) => { - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }).catch((err) => { - console.log(err) - }); - ``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the root album or directory in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Example** - - ```js - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.getRoot(options, (err, fileInfos)=>{ - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}) : Promise<FileInfo[]> - -Obtains information about the second-level album or files in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| path | string | Yes| URI of the directory to query.| -| type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<FileInfo[]> | Promise used to return the album or file information obtained.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Obtain all files in the directory. You can use getRoot to obtain the directory URI. - filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "file_folder"); - let path = file.path; - filemanager.listFile(path, "file").then((files) => { - console.log("files:" + JSON.stringify(files)); - }).catch((err) => { - console.log("failed to get files" + err); - }); - }).catch((err) => { - console.log("failed to get root" + err); - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void - -Obtains information about the second-level album or files in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | URI of the directory to query. | -| type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - -```js -// Obtain all files in the directory. You can use getRoot to obtain the directory URI. -filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "image_album"); - let path = file.path; - filemanager.listFile(path, "image",function(err, files){ - console.log("files:" + JSON.stringify(files)); - }) -}).catch((err) => { - console.log("failed to get root" + err); -}); -``` - -## filemanager.createFile - -createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> - -Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| filename | string | Yes| Name of the file to create.| -| path | string | Yes| URI of the file to create.| -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - -**Return value** - -| Type| Description| -| --- | -- | -| Promise<string> | Promise used to return the URI of the file created.| - -**Error** - -| Error Info| Error Code|Description| -| -- | --- | -- | -| Operation not permitted | 1 | A file with the same name already exists.| -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service.| -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - let media_path = "" // Obtain the file URI using listFile() and getRoot(). - let name = "xxx.jpg" // File to be saved. - filemanager.createFile(media_path, name).then((uri) => { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }).catch((err) => { - console.log(err); - }); - ``` - -## filemanager.createFile - -createFile(path : string, filename: string, options? : {dev? : DevInfo}, callback : AsyncCallback<string>) : void - -Creates a file in the specified path in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileService - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| filename | string | Yes | Name of the file to create. | -| path | string | Yes | URI of the file to create. | -| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - -**Error** - -| Error Info | Error Code| Description | -| ------------------------- | ------ | ------------------------- | -| Operation not permitted | 1 | A file with the same name already exists. | -| No such file or directory | 2 | The directory or album of the specified URI does not exist.| -| No such process | 3 | Failed to obtain the FMS service. | -| Not a directory | 20 | The object specified by the URI is not a directory or album.| - -**Example** - - ```js - // Create a file. - // Call listFile() and getRoot() to obtain the file URI. - let media_path = "" - // File to be saved. - let name = "xxx.jpg" - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.createFile(media_path, name, options, function(err, uri) { - // The URI of the file created is returned. - console.log("file uri:"+uri); - }); - - ``` - -## FileInfo -Defines the file information returned by **getRoot()** or **listFile()**. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type| Readable| Writable| Description| -| --- | -- | -- | -- | -- | -| name | string | Yes| No| File name.| -| path | string | Yes| No| URI of the file.| -| type | string | Yes| No| File type.| -| size | number | Yes| No| File size.| -| addedTime | number | Yes| No| Time when the file was scanned to the database.| -| modifiedTime | number | Yes| No| Time when the file was modified.| - -## DevInfo - -Defines the device type. - -**System capability**: SystemCapability.FileManagement.UserFileService - -### Attributes - -| Name| Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | -------- | -| name | string | Yes | Yes | Device name.| 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/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index 46e4b416c4bc0ee3389c493a540e2a7bb375bd3a..d14e06d8a3a83329a2a6e2b508508e03c93aea4c 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -1,4 +1,4 @@ -# JavaScript-based Web-like Development Paradigm +# JavaScript-compatible Web-like Development Paradigm - Universal Component Information - [Universal Attributes](js-components-common-attributes.md) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index b02f86a0da6ad041fac054cd5faf003c98755bbb..f6425d937129086d130562d8454da03bcaef3c87 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -172,7 +172,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. + oncancel="textoncancel" class="pickertext"> 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-js/js-components-svg-animatetransform.md b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md index 4b4cf63bcb25cd7e8a7abc010ae91af3bb308ad6..1cb9c1f4eb4520ab4e85193353fd0798d23158ca 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animatetransform.md @@ -1,21 +1,22 @@ -# animateTransform +# animateTransform The **** component is used to apply a transform animation and supports the following components: , , , , , , , ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>**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 The **animate** attributes and the attributes in the following table are supported. @@ -46,7 +47,7 @@ The **animate** attributes and the attributes in the following table are suppo -## Example +## Example ``` diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 9f7f8eee53a8010ef0a5ee0dfd860af3b503ec8d..0f5ff9e7a6546f55133b805e794aeb19a7fce1a8 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -1,4 +1,4 @@ -# TypeScript-based Declarative Development Paradigm +# ArkTS-based Declarative Development Paradigm - Universal Component Information - Universal Events @@ -133,12 +133,13 @@ - Canvas Components - [Canvas](ts-components-canvas-canvas.md) - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](ts-components-canvas-lottie.md) - - [Path2D](ts-components-canvas-path2d.md) - [CanvasGradient](ts-components-canvas-canvasgradient.md) - [ImageBitmap](ts-components-canvas-imagebitmap.md) - [ImageData](ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) + - [Path2D](ts-components-canvas-path2d.md) + - [Lottie](ts-components-canvas-lottie.md) + - Animation - [AnimatorProperty](ts-animatorproperty.md) - [Explicit Animation](ts-explicit-animation.md) @@ -147,8 +148,7 @@ - [Component Transition](ts-transition-animation-component.md) - [Transition of Shared Elements](ts-transition-animation-shared-elements.md) - [Motion Path Animation](ts-motion-path-animation.md) - - [Matrix Transformation](ts-matrix-transformation.md) - - [Interpolation Calculation](ts-interpolation-calculation.md) + - Global UI Methods - Pop-up Window - [Alert Dialog Box](ts-methods-alert-dialog-box.md) @@ -159,3 +159,4 @@ - [Text Picker Dialog Box](ts-methods-textpicker-dialog.md) - [Menu](ts-methods-menu.md) - [Built-in Enums](ts-appendix-enums.md) +- [Types](ts-types.md) diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png new file mode 100644 index 0000000000000000000000000000000000000000..c564bb26b539f1e48acbdb7f2aeeca8df4e4e798 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872492.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png new file mode 100644 index 0000000000000000000000000000000000000000..6c136313fe0c8774d1209a398d16ecc4b58c2bcd Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872498.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png new file mode 100644 index 0000000000000000000000000000000000000000..3e7218eb57566d86457a9fbd4a8ed0f0dd490c3f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193872526.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png new file mode 100644 index 0000000000000000000000000000000000000000..a07986a04b7477eec14c81d08e442d7b332dab83 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032458.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png new file mode 100644 index 0000000000000000000000000000000000000000..3d93b0a0a8f5d0b527d407e450a4a13a1de991ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032462.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png new file mode 100644 index 0000000000000000000000000000000000000000..5c0a336a56d0e5a186bd235cd25f9f5e5e7e644f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032480.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png new file mode 100644 index 0000000000000000000000000000000000000000..2b9bc96da366d53da784c92620a69f602f7bff14 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194032666.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png new file mode 100644 index 0000000000000000000000000000000000000000..27556ea43f7c2ecc65b9425e243ea593f02b08ec Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png new file mode 100644 index 0000000000000000000000000000000000000000..2a5c5649cc0716abc024aa3656924a456216a4c2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194192440.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png new file mode 100644 index 0000000000000000000000000000000000000000..00097d258d585ec8ad981703c5b265679e867133 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352436.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png new file mode 100644 index 0000000000000000000000000000000000000000..1b1cedac00a77279faa829636bc85028fb5ec711 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352442.png differ 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/figures/en-us_image_0000001238712471.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png new file mode 100644 index 0000000000000000000000000000000000000000..81710c1186a0c0448d70a443db66c09a4e46d395 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238712471.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png new file mode 100644 index 0000000000000000000000000000000000000000..5c75654b85d596a346fa5d793ca84991fe859a86 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832389.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png new file mode 100644 index 0000000000000000000000000000000000000000..defc3c9eb037c06b894ee2e30563facb8c8375ab Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238832413.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png new file mode 100644 index 0000000000000000000000000000000000000000..abc9a5667500a749dbceee88aef4caebf5d9df18 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952377.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png new file mode 100644 index 0000000000000000000000000000000000000000..241fe8546ea2acfdb7baf2c5e66a8af2f0d7b593 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001238952387.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png new file mode 100644 index 0000000000000000000000000000000000000000..19e99b9ef490fff79e64e33192c97c1a39c6edf9 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777778.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png new file mode 100644 index 0000000000000000000000000000000000000000..4558b332925757d97d70ee57182c260804629346 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777779.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png new file mode 100644 index 0000000000000000000000000000000000000000..9b35e8e0fc4bb514584813b79e8889cfe65649a7 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777780.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png new file mode 100644 index 0000000000000000000000000000000000000000..9e0a95f73b1aec44e6bccd6750a1c9f2815178ee Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000127777781.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 0b89c6f7d39270890a4f3fb97b269ce7bbeb3e2f..d4982a55e1b4b12ecc09658f6cc5af50f4c804d2 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -6,6 +6,8 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + + ## APIs CanvasRenderingContext2D(setting: RenderingContextSetting) @@ -721,6 +723,7 @@ Draws an outlined rectangle on the canvas. struct StrokeRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -764,16 +767,17 @@ Clears the content in a rectangle on the canvas. struct ClearRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') + .backgroundColor('#ffffff') .onReady(() =>{ this.context.fillStyle = 'rgb(0,0,255)' - this.context.fillRect(0,0,500,500) - this.context.clearRect(20,20,150,100) + this.context.fillRect(20,20,200,200) + this.context.clearRect(30,30,150,100) }) } .width('100%') @@ -809,6 +813,7 @@ Draws filled text on the canvas. struct FillText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -853,6 +858,7 @@ Draws a text stroke on the canvas. struct StrokeText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -921,6 +927,7 @@ Measures the specified text to obtain its width. This API returns a **TextMetric struct MeasureText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -973,6 +980,8 @@ Strokes a path. .onReady(() =>{ this.context.moveTo(25, 25) this.context.lineTo(25, 105) + this.context.lineTo(75, 105) + this.context.lineTo(75, 25) this.context.strokeStyle = 'rgb(0,0,255)' this.context.stroke() }) @@ -1435,7 +1444,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.context.beginPath() - this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.context.stroke() }) } @@ -1503,7 +1512,7 @@ Fills the area inside a closed path on the canvas. | Name | Type | Mandatory | Default Value | Description | | -------- | -------------- | ---- | --------- | ---------------------------------------- | -| fillRule | CanvasFillRule | No | "nonzero" | Specifies the rule to populate the object.
The options are **"nonzero"** and **"evenodd"**.| +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| **Example** @@ -1616,11 +1625,11 @@ Sets the current path to a clipping area. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.rect(0, 0, 200, 200) + this.context.rect(0, 0, 100, 200) this.context.stroke() this.context.clip() this.context.fillStyle = "rgb(255,0,0)" - this.context.fillRect(0, 0, 150, 150) + this.context.fillRect(0, 0, 200, 200) }) } .width('100%') @@ -1634,7 +1643,7 @@ Sets the current path to a clipping area. clip(path: Path2D, fillRule?: CanvasFillRule): void -Sets a **Path2D** path to a clipping area. This API is a null API. +Sets the current path to a clipping path. **Parameters** @@ -1644,12 +1653,44 @@ Sets a **Path2D** path to a clipping area. This API is a null API. | fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.context.clip(region,"evenodd") + this.context.fillStyle = "rgb(255,0,0)" + this.context.fillRect(0, 0, this.context.width, this.context.height) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + ### filter filter(filter: string): void -Provides filter effects. This API is a null API. +Provides filter effects. This API is a void API. **Parameters** @@ -1662,21 +1703,21 @@ Provides filter effects. This API is a null API. getTransform(): Matrix2D -Obtains the current transformation matrix being applied to the context. This API is a null API. +Obtains the current transformation matrix being applied to the context. This API is a void API. ### resetTransform resetTransform(): void -Resets the current transform to the identity matrix. This API is a null API. +Resets the current transform to the identity matrix. This API is a void API. ### direction direction(direction: CanvasDirection): void -Sets the current text direction used to draw text. This API is a null API. +Sets the current text direction used to draw text. This API is a void API. ### rotate @@ -1751,9 +1792,10 @@ Scales the canvas based on the given scale factors. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.strokeRect(10, 10, 25, 25) + this.context.lineWidth = 3 + this.context.strokeRect(30, 30, 50, 50) this.context.scale(2, 2) // Scale to 200% - this.context.strokeRect(10, 10, 25, 25) + this.context.strokeRect(30, 30, 50, 50) }) } .width('100%') @@ -1772,6 +1814,7 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. > **NOTE** +> > The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > > - x' = scaleX \* x + skewY \* y + translateX @@ -1877,7 +1920,7 @@ Resets the existing transformation matrix and creates a new transformation matri setTransform(transform?: Matrix2D): void -Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a null API. +Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a void API. ### translate @@ -1983,7 +2026,7 @@ Draws an image on the canvas. createImageData(sw: number, sh: number): ImageData -Creates an **ImageData** object with the specified dimensions. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions. **Parameters** @@ -1993,23 +2036,21 @@ Creates an **ImageData** object with the specified dimensions. For details, see | sh | number | Yes | 0 | Height of the **ImageData** object.| -### createImageData - createImageData(imageData: ImageData): ImageData -Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | --------- | ---------------------------------------- | ---- | ---- | ----------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.| +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.| **Return value** | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2037,7 +2078,7 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. +Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas. **Parameters** @@ -2052,7 +2093,39 @@ Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | **ImageData** object.| +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| + + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ### putImageData @@ -2061,13 +2134,13 @@ putImageData(imageData: ImageData, dx: number, dy: number): void putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void -Puts data from the given **[ImageData](ts-components-canvas-imagebitmap.md)** object into the specified rectangular area on the canvas. +Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | | dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | | dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| @@ -2142,6 +2215,7 @@ Sets the dash line style. .onReady(() =>{ this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) + this.context.stroke() }) } .width('100%') @@ -2165,24 +2239,34 @@ Obtains the dash line style. | -------- | ------------------------ | | number[] | An array of numbers that specify distances to alternately draw a line and a gap.| + **Example** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { +@Entry +@Component +struct CanvasGetLineDash { + @State message: string = 'Hello World' + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.context.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) this.context.stroke(); @@ -2190,17 +2274,20 @@ Obtains the dash line style. }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) + ### imageSmoothingQuality imageSmoothingQuality(quality: imageSmoothingQuality) -Sets the quality of image smoothing. This API is a null API. +Sets the quality of image smoothing. This API is a void API. **Parameters** @@ -2220,7 +2307,7 @@ Displays the specified **ImageBitmap** object. | Name | Type | Description | | ------ | ---------------------------------------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| +| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| **Example** @@ -2228,7 +2315,7 @@ Displays the specified **ImageBitmap** object. // xxx.ets @Entry @Component - struct PutImageData { + struct TransferFromImageBitmap { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -2259,6 +2346,7 @@ Displays the specified **ImageBitmap** object. ``` ![en-us_image_000000127777773](figures/en-us_image_000000127777773.png) + ### toDataURL toDataURL(type?: string, quality?: number): string @@ -2328,7 +2416,11 @@ Restores the saved drawing context. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.restore() + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); }) } .width('100%') @@ -2336,6 +2428,7 @@ Restores the saved drawing context. } } ``` + ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### save @@ -2361,14 +2454,19 @@ Saves all states of the canvas in the stack. This API is usually called when the .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.save() - }) + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); + }) } .width('100%') .height('100%') } } ``` + ![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### createLinearGradient diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index b073ef589bb007932cca479c1a3bfc84591bde49..a8c3cf662854126929a613d1557c7d2a1025ff91 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -3,8 +3,9 @@ The **\** component can be used to customize drawings. > **NOTE** -> -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Required Permissions @@ -37,7 +38,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | ----------------------------- | ---- | -------------------- | | onReady(event: () => void) | - | Triggered when a canvas is ready. When this event is triggered, the width and height of the canvas can be obtained, and you can use the canvas APIs to draw images.| -## Example + +**Example** ```ts // xxx.ets @@ -53,8 +55,8 @@ struct CanvasExample { .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.fillRect(0,30,100,100) + .onReady(() => { + this.context.fillRect(0, 30, 100, 100) }) } .width('100%') @@ -62,3 +64,4 @@ struct CanvasExample { } } ``` + ![en-us_image_0000001194032666](figures/en-us_image_0000001194032666.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 0509567d2ffb8983abc115e92e3d34a881cc8d96..b2ebc714ee127ede15141dffaac3b47914be80c8 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -3,23 +3,27 @@ **CanvasGradient** provides a canvas gradient object. > **NOTE** -> +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## addColorStop addColorStop(offset: number, color: string): void Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color. -- Parameters + +**Parameters** + | Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | --------- | ---------------------------- | | offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.| | color | string | Yes | '#ffffff' | Gradient color to set. | -- Example + +**Example** ```ts // xxx.ets @@ -48,10 +52,6 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse .height('100%') }} ``` - - - - ![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index f5c6527207199c2331afcdd27c0809ad4a62db90..3dd7664d96505f7e18b90071dd25e4cd9eaaf99d 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -1,19 +1,49 @@ # ImageBitmap -> **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +An **ImageBitmap** object stores pixel data rendered on a canvas. +> **NOTE** +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -An **ImageBitmap** object stores pixel data rendered on a canvas. ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| width | number | Pixel width of the **ImageBitmap** object.| -| height | number | Pixel height of the **ImageBitmap** object.| +| width | number | Pixel width of the **ImageBitmap** object.| +| height | number | Pixel height of the **ImageBitmap** object.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct ImageExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage( this.img,0,0,500,500,0,0,400,200); + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ![en-us_image_0000001194352442](figures/en-us_image_0000001194352442.png) + ## Methods diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md index 6fe18b7ddaca893209a91e9ed9b339c5f8fa45f2..366da1b45bd89edb10affc51e34697d5497b21a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md @@ -1,17 +1,48 @@ # ImageData - An **ImageData** object stores pixel data rendered on a canvas. > **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| width | number | Actual width of the rectangle on the canvas, in pixels.| -| height | number | Actual height of the rectangle on the canvas, in pixels.| -| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.| +| width | number | Actual width of the rectangle on the canvas, in pixels.| +| height | number | Actual height of the rectangle on the canvas, in pixels.| +| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.| + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Translate { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index 77690f350b1b2d4290789c864998cb8ab78a51f9..8dd7d0943ced17f807da65c0aa1a8b232f39500d 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -3,13 +3,10 @@ **Lottie** allows you to implement animation-specific operations. > **NOTE** +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions - -None - ## Modules to Import @@ -32,7 +29,8 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea Loads an animation. Before calling this method, declare the **Animator('\__lottie\_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | -------------- | --------------------------- | ---- | ---------------------------------------- | | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| @@ -50,12 +48,13 @@ destroy(name: string): void Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| -- Example +**Example** ```ts // xxx.ets import lottie from '@ohos/lottieETS' @@ -130,12 +129,14 @@ play(name: string): void Plays a specified animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| -- Example +**Example** + ```ts lottie.play(this.animateName) ``` @@ -147,12 +148,14 @@ pause(name: string): void Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| -- Example +**Example** + ```ts lottie.pause(this.animateName) ``` @@ -164,12 +167,14 @@ togglePause(name: string): void Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| -- Example +**Example** + ```ts lottie.togglePause(this.animateName) ``` @@ -181,12 +186,14 @@ stop(name: string): void Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| -- Example +**Example** + ```ts lottie.stop(this.animateName) ``` @@ -198,13 +205,15 @@ setSpeed(speed: number, name: string): void Sets the playback speed of the specified animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| -- Example +**Example** + ```ts lottie.setSpeed(5, this.animateName) ``` @@ -216,13 +225,15 @@ setDirection(direction: AnimationDirection, name: string): void Sets the direction in which the specified animation plays. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| -- Example +**Example** + ```ts lottie.setDirection(-1, this.animateName) ``` @@ -262,12 +273,14 @@ play(name?: string): void Plays an animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------------- | | name | string | No | Name of the target animation. By default, the value is null.| -- Example +**Example** + ```ts this.animateItem.play() ``` @@ -279,12 +292,14 @@ destroy(name?: string): void Destroys an animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------------- | | name | string | No | Name of the target animation. By default, the value is null.| -- Example +**Example** + ```ts this.animateItem.destroy() ``` @@ -296,12 +311,14 @@ pause(name?: string): void Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------------- | | name | string | No | Name of the target animation. By default, the value is null.| -- Example +**Example** + ```ts this.animateItem.pause() ``` @@ -313,12 +330,14 @@ togglePause(name?: string): void Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------------- | | name | string | No | Name of the target animation. By default, the value is null.| -- Example +**Example** + ```ts this.animateItem.togglePause() ``` @@ -330,12 +349,14 @@ stop(name?: string): void Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------------- | | name | string | No | Name of the target animation. By default, the value is null.| -- Example +**Example** + ```ts this.animateItem.stop() ``` @@ -347,12 +368,14 @@ setSpeed(speed: number): void Sets the playback speed of an animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| -- Example +**Example** + ```ts this.animateItem.setSpeed(5); ``` @@ -364,12 +387,14 @@ setDirection(direction: AnimationDirection): void Sets the playback direction of an animation. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1.| -- Example +**Example** + ```ts this.animateItem.setDirection(-1) ``` @@ -381,14 +406,16 @@ goToAndStop(value: number, isFrame?: boolean): void Sets the animation to stop at the specified frame or time. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.| | name | string | No | Name of the target animation. By default, the value is null. | -- Example +**Example** + ```ts // Set the animation to stop at the specified frame. this.animateItem.goToAndStop(25, true) @@ -403,14 +430,16 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void Sets the animation to start from the specified frame or time progress. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| | name | string | No | Name of the target animation. By default, the value is null. | -- Example +**Example** + ```ts // Set the animation to stop at the specified frame. this.animateItem.goToAndPlay(25, true) @@ -425,13 +454,15 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean Sets the animation to play only the specified segment. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ---------------------------------------- | | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | -- Example +**Example** + ```ts // Set the animation to play the specified segment. this.animateItem.playSegments([10, 20], false) @@ -446,12 +477,14 @@ resetSegments(forceFlag: boolean): void Resets the settings configured by the **playSegments** method to play all the frames. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.| -- Example +**Example** + ```ts this.animateItem.resetSegments(true) ``` @@ -463,7 +496,8 @@ resize(): void Resizes the animation layout. -- Example +**Example** + ```ts this.animateItem.resize() ``` @@ -475,12 +509,14 @@ setSubframe(useSubFrame: boolean): void Sets the precision of the **currentFrame** attribute to display floating-point numbers. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ------------ | ------- | ---- | ---------------------------------------- | | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| -- Example +**Example** + ```ts this.animateItem.setSubframe(false) ``` @@ -492,12 +528,14 @@ getDuration(inFrames?: boolean): void Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | -------- | ------- | ---- | ---------------------------------------- | - | inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms. The default value is **false**.| + | inFrames | boolean | No | Whether to obtain the duration or number of frames.
**true**: number of frames.
**false**: duration, in ms.
Default value: **false**| + +**Example** -- Example ```ts this.animateItem.getDuration(true) ``` @@ -509,13 +547,15 @@ addEventListener<T = any>(name: AnimationEventName, callback: AnimationEve Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| | callback | AnimationEventCallback<T> | Yes | Custom callback. | -- Example +**Example** + ```ts private callbackItem: any = function() { console.log("grunt loopComplete") @@ -533,13 +573,15 @@ removeEventListener<T = any>(name: AnimationEventName, callback?: Animatio Removes an event listener. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| | callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | -- Example +**Example** + ```ts this.animateItem.removeEventListener('loopComplete', this.animateName) ``` @@ -551,13 +593,15 @@ triggerEvent<T = any>(name: AnimationEventName, args: T): void Directly triggers all configured callbacks of a specified event. -- Parameters +**Parameters** + | Name | Type | Mandatory | Description | | ---- | ------------------ | ---- | --------- | | name | AnimationEventName | Yes | Animation event type. | | args | any | Yes | Custom callback parameters.| -- Example +**Example** + ```ts private triggerCallBack: any = function(item) { console.log("trigger loopComplete, name:" + item.name) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index 7e30f52d8c730b6ec0527b24d1eeefd31a3c4d91..e8c6fea764e26339c247c5d501f89032d8163dbf 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -1,11 +1,11 @@ # Path2D -> **NOTE** -> -> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. +> **NOTE** +> +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. ## addPath @@ -16,11 +16,11 @@ Adds a path to this path. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| path | path2D | Yes| - | Path to be added to this path.| -| transform | Matrix2D | No| null | Transformation matrix of the new path.| - + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | path | path2D | Yes| - | Path to be added to this path.| + | transform | Matrix2D | No| null | Transformation matrix of the new path.| + **Example** @@ -103,10 +103,10 @@ Moves the current coordinate point of the path to the target point, without draw **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the target point.| -| y | number | Yes| 0 | Y-coordinate of the target point.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the target point.| + | y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -150,10 +150,10 @@ Draws a straight line from the current point to the target point. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the target point.| -| y | number | Yes| 0 | Y-coordinate of the target point.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the target point.| + | y | number | Yes| 0 | Y-coordinate of the target point.| **Example** @@ -198,14 +198,14 @@ Draws a cubic bezier curve on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| -| cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| -| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| -| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| -| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| -| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.| + | cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.| + | cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.| + | cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.| + | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| + | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -226,7 +226,8 @@ Draws a cubic bezier curve on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.path2Db.moveTo(10, 10) - this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20);this.context.stroke(this.path2Db) + this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -246,12 +247,12 @@ Draws a quadratic curve on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| -| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| -| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| -| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.| + | cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.| + | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.| + | y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.| **Example** @@ -293,14 +294,14 @@ Draws an arc on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the center point of the arc.| -| y | number | Yes| 0 | Y-coordinate of the center point of the arc.| -| radius | number | Yes| 0 | Radius of the arc.| -| startAngle | number | Yes| 0 | Start radian of the arc.| -| endAngle | number | Yes| 0 | End radian of the arc.| -| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the center point of the arc.| + | y | number | Yes| 0 | Y-coordinate of the center point of the arc.| + | radius | number | Yes| 0 | Radius of the arc.| + | startAngle | number | Yes| 0 | Start radian of the arc.| + | endAngle | number | Yes| 0 | End radian of the arc.| + | counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.| **Example** @@ -320,7 +321,8 @@ Draws an arc on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.arc(100, 75, 50, 0, 6.28);this.context.stroke(this.path2Db) + this.path2Db.arc(100, 75, 50, 0, 6.28) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -340,13 +342,13 @@ Draws an arc based on the radius and points on the arc. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| -| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| -| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| -| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| -| radius | number | Yes| 0 | Radius of the arc.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x1 | number | Yes| 0 | X-coordinate of the first point on the arc.| + | y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.| + | x2 | number | Yes| 0 | X-coordinate of the second point on the arc.| + | y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.| + | radius | number | Yes| 0 | Radius of the arc.| **Example** @@ -387,16 +389,16 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the ellipse center.| -| y | number | Yes| 0 | Y-coordinate of the ellipse center.| -| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| -| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| -| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| -| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| -| counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**. | + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the ellipse center.| + | y | number | Yes| 0 | Y-coordinate of the ellipse center.| + | radiusX | number | Yes| 0 | Ellipse radius on the x-axis.| + | radiusY | number | Yes| 0 | Ellipse radius on the y-axis.| + | rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.| + | startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.| + | endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.| + | counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**.| **Example** @@ -408,7 +410,7 @@ Draws an ellipse in the specified rectangular region on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -416,7 +418,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI*2) this.context.stroke(this.path2Db) }) } @@ -437,12 +439,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| -| w | number | Yes| 0 | Width of the rectangle.| -| h | number | Yes| 0 | Height of the rectangle.| + | Name| Type| Mandatory| Default Value| Description| + | -------- | -------- | -------- | -------- | -------- | + | x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.| + | y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.| + | w | number | Yes| 0 | Width of the rectangle.| + | h | number | Yes| 0 | Height of the rectangle.| **Example** @@ -462,7 +464,8 @@ Creates a rectangle on the canvas. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.rect(20, 20, 100, 100);this.context.stroke(this.path2Db) + this.path2Db.rect(20, 20, 100, 100); + this.context.stroke(this.path2Db) }) } .width('100%') 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-interpolation-calculation.md b/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md deleted file mode 100644 index 029a61c9f47bfb216d507b70845c3fc6877ca697..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md +++ /dev/null @@ -1,277 +0,0 @@ -# Interpolation Calculation - -Interpolation calculation can be implemented to set the animation interpolation curve, which is used to construct the step curve, cubic Bezier curve, and spring curve objects. - -> **NOTE** -> -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import Curves from '@ohos.curves' -``` - - -## Curves.initCurve9+ - -initCurve(curve?: Curve): ICurve - - -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve | [Curve](#curve-enums)| No | Curve.Linear | Curve type.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Interpolation object of the curve.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -``` - - -## Curves.stepsCurve9+ - -stepsCurve(count: number, end: boolean): ICurve - - -Constructs a step curve object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end point of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.stepsCurve(9, true) // Create a step curve. -``` - - -## Curves.cubicBezierCurve9+ - -cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve - - -Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. -``` - - -## Curves.springCurve9+ - -springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve - - -Constructs a spring curve object. - - -**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.springCurve(100, 1, 228, 30) // Create a spring curve. -``` - - -## ICurve - - -### interpolate - -interpolate(fraction: number): number - - -Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | -------------------------------------------- | -| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| - -**Return value** - -| Type | Description | -| ------ | ------------------------------------ | -| number | The curve interpolation corresponding to the normalized time point is returned.| - -**Example** - -```ts -import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. -``` - - -## Curves.init(deprecated) - -init(curve?: Curve): string - - -Implements initialization to create a curve object based on the input parameter. This API is deprecated since API version 9. Use [Curves.initCurve](#curvesinitcurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve |[Curve](#curve-enums)| No | Curve.Linear | Curve type.| - - -## Curves.steps(deprecated) - -steps(count: number, end: boolean): string - - -Constructs a step curve object. This API is deprecated since API version 9. Use [Curves.stepsCurve](# curvesstepscurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - - -## Curves.cubicBezier(deprecated) - -cubicBezier(x1: number, y1: number, x2: number, y2: number): string - - -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - - -## Curves.spring(deprecated) - -spring(velocity: number, mass: number, stiffness: number, damping: number): string - - -Constructs a spring curve object. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| -| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.| - - -## Curve - -| Name | Description | -| ------------------- | ---------------------------------------- | -| Linear | The animation speed keeps unchanged. | -| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| -| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.| -| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.| -| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.| -| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).| -| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).| -| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0).| -| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).| -| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).| -| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).| -| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).| -| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).| - - -## Example - -```ts -// xxx.ets -import Curves from '@ohos.curves' -@Entry -@Component -struct ImageComponent { - @State widthSize: number = 200 - @State heightSize: number = 200 - build() { - Column() { - Text() - .margin({top:100}) - .width(this.widthSize) - .height(this.heightSize) - .backgroundColor(Color.Red) - .onClick(()=> { - let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); - this.widthSize = curve.interpolate(0.5) * this.widthSize; - this.heightSize = curve.interpolate(0.5) * this.heightSize; - }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) - }.width("100%").height("100%") - } -} -``` -![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md b/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md deleted file mode 100644 index 34f1738c2085bd8c77e6c69f43845a37bbc98985..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md +++ /dev/null @@ -1,441 +0,0 @@ -# Matrix Transformation - -Matrix transformation enables you to rotate, scale, skew, or translate an image. - -> **NOTE** -> -> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```ts -import matrix4 from '@ohos.matrix4' -``` - - -## matrix4.init - -init(array: Array<number>): Matrix4Transit - - -Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | ------------------------------------------------------------ | -| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | 4x4 matrix object created based on the input parameter.| - -**array** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------------- | -| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the identity matrix. | -| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | -| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | -| m03 | number | Yes | Meaningless. | -| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | -| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the identity matrix. | -| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | -| m13 | number | Yes | Meaningless. | -| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | -| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | -| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the identity matrix. | -| m23 | number | Yes | Meaningless. | -| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the identity matrix.| -| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the identity matrix.| -| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the identity matrix.| -| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// Create a 4x4 matrix. -let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix) - } - } -} -``` - - -## matrix4.identity - -identity(): Matrix4Transit - - -Matrix initialization function. Can return an identity matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------- | -| Matrix4Transit | Identity matrix object.| - -**Example** - -```ts -// The effect of matrix 1 is the same as that of matrix 2. -import matrix4 from '@ohos.matrix4' -let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -let matrix2 = matrix4.identity() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix1) - Image($r("app.media.zh")) - .width("40%") - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -## matrix4.copy - -copy(): Matrix4Transit - - -Matrix copy function, which is used to copy the current matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------------- | -| Matrix4Transit | Copy object of the current matrix.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) - - build() { - Column() { - Image($r("app.media.bg1")) - .width("40%") - .height(100) - .transform(this.matrix1) - Image($r("app.media.bg2")) - .width("40%") - .height(100) - .margin({top:50}) - .transform(this.matrix2) - } - } -} -``` - -![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png) - - -## Matrix4 - - -### combine - -combine(matrix: Matrix4): Matrix4Transit - - -Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------ | -| matrix | Matrix4 | Yes | Matrix object to be overlaid.| - -**Return value** - -| Type | Description | -| -------------- | ------------------ | -| Matrix4Transit | Object after matrix overlay.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() - - build() { - Column() { - // Before matrix transformation - Image($r("app.media.icon")) - .width("40%") - .height(100) - .margin({top:50}) - // Translate the x-axis by 200px, and then scale down the x-axis twice. - Image($r("app.media.icon")) - .transform(this.matrix1.combine(this.matrix2)) - .width("40%") - .height(100) - .margin({top:50}) - } - } -} -``` - -![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png) - - -### invert - -invert(): Matrix4Transit - - -Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect. - -**Return value** - -| Type | Description | -| -------------- | ---------------------- | -| Matrix4Transit | Inverse matrix object of the current matrix.| - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) -let matrix2 = matrix1.invert() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width(200) - .height(100) - .transform(matrix1) - .margin({ top: 100 }) - Image($r("app.media.zh")) - .width(200) - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -### translate - -translate({x?: number, y?: number, z?: number}): Matrix4Transit - - -Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix. - -**Parameter** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| x | number | No | Translation distance of the x-axis, in px.
Default value: **0**| -| y | number | No | Translation distance of the y-axis, in px.
Default value: **0**| -| z | number | No | Translation distance of the z-axis, in px.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the translation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png) - - -### scale - -scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit - - -Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | Scaling multiple of the x-axis.
Default value: **1** | -| y | number | No | Scaling multiple of the y-axis.
Default value: **1** | -| z | number | No | Scaling multiple of the z-axis.
Default value: **1** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the scaling effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![zh-cn_image_0000001219864131](figures/zh-cn_image_0000001219864131.png) - - -### rotate - -rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit - - -Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | X coordinate of the rotation axis vector.
Default value: **1** | -| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1** | -| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1** | -| angle | number | No | Rotation angle.
Default value: **0** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the rotation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - }.width("100%").margin({top:50}) - } -} -``` - -![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png) - - -### transformPoint - -transformPoint(point: Point): Point - - -Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------ | -| point | Point | Yes | Point to be transformed.| - -**Return value** - -| Type | Description | -| ----- | ---------------- | -| Point | Point object after matrix transformation| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -import prompt from '@system.prompt' - -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().transformPoint([100, 10]) - - build() { - Column() { - Button("get Point") - .onClick(() => { - prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000}) - }).backgroundColor(0x2788D9) - }.width("100%").padding(50) - } -} -``` - -![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 8fc5a51f8ce0dfa8f141d000348257dae7fddfd9..5b082bc803d6d82e93c273fc1ea9ba4ddfd25ce1 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -2,47 +2,46 @@ Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency. - > **NOTE** -> +> > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + ## APIs OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | ------------------------------ | -| width | number | Yes | - | Width of the offscreen canvas. | -| height | number | Yes | - | Height of the offscreen canvas. | -| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------ | +| width | number | Yes | Width of the offscreen canvas. | +| height | number | Yes | Height of the offscreen canvas. | +| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | See RenderingContextSettings.| ## Attributes -| Name | Type | Description | -| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineWidth](#linewidth) | number | Line width. | -| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'** | -| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'** | -| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10** | -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'** | -| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
**NOTE**
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'** | -| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'** | -| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | -| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0** | -| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'** | -| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0** | -| [shadowColor](#shadowcolor) | string | Shadow color. | -| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | -| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true** | -| imageSmoothingQuality | string | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**.
- Default value: **'low'** | +| Name | Type | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is **string**, this attribute indicates the color of the filling area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineWidth](#linewidth) | number | Line width. | +| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
- Default value: **'butt'**| +| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
- Default value: **'miter'**| +| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
- Default value: **10**| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
(Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **'normal normal 14px sans-serif'**| +| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
> **NOTE**
> In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
- Default value: **'left'**| +| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
- Default value: **'alphabetic'**| +| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
- Default value: **0.0**| +| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
- Default value: **'source-over'**| +| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
- Default value: **0.0**| +| [shadowColor](#shadowcolor) | string | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
- Default value: **true**| > **NOTE** > @@ -574,8 +573,7 @@ struct ShadowColor { this.offContext.shadowColor = 'rgb(0,0,255)' this.offContext.fillStyle = 'rgb(255,0,0)' this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap -() + var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -769,6 +767,7 @@ Draws an outlined rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -815,6 +814,7 @@ Clears the content in a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -823,8 +823,8 @@ Clears the content in a rectangle on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0,0,500,500) - this.offContext.clearRect(20,20,150,100) + this.offContext.fillRect(20,20,200,200) + this.offContext.clearRect(30,30,150,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -846,12 +846,12 @@ Draws filled text on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width allowed for the text.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width allowed for the text. | **Example** @@ -863,6 +863,7 @@ Draws filled text on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -893,12 +894,12 @@ Draws a text stroke on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | --------------- | -| text | string | Yes | "" | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width of the text to be drawn.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | "" | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width of the text to be drawn. | **Example** @@ -910,6 +911,7 @@ Draws a text stroke on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -950,12 +952,12 @@ Returns a **TextMetrics** object used to obtain the width of specified text. | ----------- | ------- | | TextMetrics | **TextMetrics** object.| -**TextMetrics** +**TextMetrics** attributes -| Name | Type | Description | -| ----- | ------ | ------- | -| width | number | Width of the text.| -| height | number | Height of the text.| +| Name | Type | Description | +| ------------------------ | ------ | ---------------------------------------- | +| width | number | Width of the text. | +| height | number | Height of the text. | | actualBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle used to render the text. The current value is **0**.| | actualBoundingBoxLeft | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the left side of the bounding rectangle of the text. The current value is **0**.| @@ -978,6 +980,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1014,7 +1017,7 @@ Strokes a path. | path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.| **Example** - + ```ts // xxx.ets @Entry @@ -1023,6 +1026,7 @@ Strokes a path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1032,6 +1036,8 @@ Strokes a path. .onReady(() =>{ this.offContext.moveTo(25, 25) this.offContext.lineTo(25, 105) + this.offContext.lineTo(75, 105) + this.offContext.lineTo(75, 25) this.offContext.strokeStyle = 'rgb(0,0,255)' this.offContext.stroke() var image = this.offContext.transferToImageBitmap() @@ -1063,6 +1069,7 @@ Creates a drawing path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1112,6 +1119,7 @@ Moves a drawing path to a target position on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1159,6 +1167,7 @@ Connects the current point to a target position using a straight line. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1199,6 +1208,7 @@ Draws a closed path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1240,9 +1250,9 @@ Creates a pattern for image filling based on a specified source image and repeti **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| +| Type | Description | +| ------------------------------- | ----------------------- | +| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| **Example** @@ -1255,6 +1265,7 @@ Creates a pattern for image filling based on a specified source image and repeti private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1305,6 +1316,7 @@ Draws a cubic bezier curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1354,6 +1366,7 @@ Draws a quadratic curve on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1386,13 +1399,13 @@ Draws an arc on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ---------- | -| x | number | Yes | 0 | X-coordinate of the center point of the arc.| -| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| -| radius | number | Yes | 0 | Radius of the arc. | -| startAngle | number | Yes | 0 | Start radian of the arc. | -| endAngle | number | Yes | 0 | End radian of the arc. | +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ---------- | +| x | number | Yes | 0 | X-coordinate of the center point of the arc.| +| y | number | Yes | 0 | Y-coordinate of the center point of the arc.| +| radius | number | Yes | 0 | Radius of the arc. | +| startAngle | number | Yes | 0 | Start radian of the arc. | +| endAngle | number | Yes | 0 | End radian of the arc. | | counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.| **Example** @@ -1405,6 +1418,7 @@ Draws an arc on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1454,6 +1468,7 @@ Draws an arc based on the radius and points on the arc. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1485,15 +1500,15 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------------- | ------- | ---- | ----- | ----------------- | -| x | number | Yes | 0 | X-coordinate of the ellipse center. | -| y | number | Yes | 0 | Y-coordinate of the ellipse center. | -| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | -| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | -| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | -| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ----------------- | +| x | number | Yes | 0 | X-coordinate of the ellipse center. | +| y | number | Yes | 0 | Y-coordinate of the ellipse center. | +| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | +| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | +| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | +| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| +| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| | counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. | **Example** @@ -1514,7 +1529,7 @@ Draws an ellipse in the specified rectangular region on the canvas. .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.beginPath() - this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -1537,12 +1552,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| -| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| -| w | number | Yes | 0 | Width of the rectangle. | -| h | number | Yes | 0 | Height of the rectangle. | +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.| +| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.| +| w | number | Yes | 0 | Width of the rectangle. | +| h | number | Yes | 0 | Height of the rectangle. | **Example** @@ -1554,6 +1569,7 @@ Creates a rectangle on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1578,11 +1594,15 @@ Creates a rectangle on the canvas. ### fill -fill(): void +fill(fillRule?: CanvasFillRule): void Fills the area inside a closed path on the canvas. - **Example** +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| ```ts // xxx.ets @@ -1592,6 +1612,7 @@ Fills the area inside a closed path on the canvas. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1614,12 +1635,73 @@ Fills the area inside a closed path on the canvas. ![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.png) +fill(path: Path2D, fillRule?: CanvasFillRule): void + +Fills the area inside a closed path on the canvas. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to fill. | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.| + + +**Example** + +```ts +// xxx.ets +@Entry +@Component +struct Fill { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.moveTo(30, 90); + region.lineTo(110, 20); + region.lineTo(240, 130); + region.lineTo(60, 130); + region.lineTo(190, 20); + region.lineTo(270, 90); + region.closePath(); + // Fill path + this.offContext.fillStyle = 'green'; + this.offContext.fill(region, "evenodd"); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![en-us_image_000000127777775](figures/en-us_image_000000127777775.png) + + + ### clip -clip(): void +clip(fillRule?: CanvasFillRule): void Sets the current path to a clipping path. +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + **Example** ```ts @@ -1630,6 +1712,7 @@ Sets the current path to a clipping path. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1637,11 +1720,11 @@ Sets the current path to a clipping path. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(0, 0, 200, 200) + this.offContext.rect(0, 0, 100, 200) this.offContext.stroke() this.offContext.clip() this.offContext.fillStyle = "rgb(255,0,0)" - this.offContext.fillRect(0, 0, 150, 150) + this.offContext.fillRect(0, 0, 200, 200) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1655,6 +1738,89 @@ Sets the current path to a clipping path. ![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png) +clip(path:Path2D, fillRule?: CanvasFillRule): void + +Sets a closed path to a clipping path. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | Yes | | A **Path2D** path to clip.| +| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.| + + **Example** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.offContext.clip(region,"evenodd") + this.offContext.fillStyle = "rgb(255,0,0)" + this.offContext.fillRect(0, 0, 600, 600) + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + + + +### filter + +filter(filter: string): void + +Sets a filter for the image on the canvas. This API is a void API. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ------ | ------ | ---- | ---- | ------------ | +| filter | string | Yes | - | Functions that accept various filter effects.| + + +### getTransform + +getTransform(): Matrix2D + +Obtains the current transformation matrix being applied to the context. This API is a void API. + + +### resetTransform + +resetTransform(): void + +Resets the current transform to the identity matrix. This API is a void API. + + +### direction + +direction(direction: CanvasDirection): void + +Sets the text direction for drawing text. This API is a void API. + + ### rotate rotate(angle: number): void @@ -1663,8 +1829,8 @@ Rotates a canvas clockwise around its coordinate axes. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ------ | ---- | ---- | ---------------------------------------- | | angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| **Example** @@ -1677,6 +1843,7 @@ Rotates a canvas clockwise around its coordinate axes. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1722,6 +1889,7 @@ Scales the canvas based on scale factors. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1729,9 +1897,10 @@ Scales the canvas based on scale factors. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.lineWidth = 3 + this.offContext.strokeRect(30, 30, 50, 50) this.offContext.scale(2, 2) // Scale to 200% - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.strokeRect(30, 30, 50, 50) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1761,14 +1930,14 @@ Defines a transformation matrix. To transform a graph, you only need to set para **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1780,6 +1949,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1812,18 +1982,18 @@ Defines a transformation matrix. To transform a graph, you only need to set para setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | -| ---------- | ------ | ---- | ---- | -------- | -| a | number | Yes | 0 |X-axis scale.| -| b | number | Yes | 0 |X-axis skew.| -| c | number | Yes | 0 |Y-axis skew.| -| d | number | Yes | 0 |Y-axis scale.| -| e | number | Yes | 0 |X-axis translation.| -| f | number | Yes | 0 |Y-axis translation.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | -------------------- | +| a | number | Yes | 0 | X-axis scale. | +| b | number | Yes | 0 | X-axis skew. | +| c | number | Yes | 0 | Y-axis skew. | +| d | number | Yes | 0 | Y-axis scale. | +| e | number | Yes | 0 | X-axis translation.| +| f | number | Yes | 0 | Y-axis translation.| **Example** @@ -1835,6 +2005,7 @@ Resets the existing transformation matrix and creates a new transformation matri private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1857,8 +2028,10 @@ Resets the existing transformation matrix and creates a new transformation matri } ``` - ![zh-cn_image_0000001193872526](figures/zh-cn_image_0000001193872526.png) + ![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png) + +### translate ### translate @@ -1868,7 +2041,7 @@ Moves the origin of the coordinate system. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | -------- | | x | number | Yes | 0 | X-axis translation.| | y | number | Yes | 0 | Y-axis translation.| @@ -1883,6 +2056,7 @@ Moves the origin of the coordinate system. private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1903,7 +2077,7 @@ Moves the origin of the coordinate system. } ``` - ![en-us_image_0000001256978373](figures/en-us_image_0000001256978373.png) + ![en-us_image_0000001238832413](figures/en-us_image_0000001238832413.png) ### drawImage @@ -1918,17 +2092,17 @@ Draws an image on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------- | ---------------------------------------- | ---- | ---- | -------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| -| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image.| -| sw | number | No | 0 | Target width to crop the source image. | -| sh | number | No | 0 | Target height to crop the source image. | -| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | -| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas.| -| dw | number | No | 0 | Width of the drawing area. | -| dh | number | No | 0 | Height of the drawing area. | +| Name | Type | Mandatory | Default Value | Description | +| ----- | ---------------------------------------- | ---- | ---- | ----------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.| +| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | +| sw | number | No | 0 | Target width to crop the source image. | +| sh | number | No | 0 | Target height to crop the source image. | +| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | +| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. | +| dw | number | No | 0 | Width of the drawing area. | +| dh | number | No | 0 | Height of the drawing area. | **Example** @@ -1937,7 +2111,7 @@ Draws an image on the canvas. // xxx.ets @Entry @Component - struct Index { + struct DrawImage { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -1967,33 +2141,31 @@ Draws an image on the canvas. createImageData(sw: number, sh: number): ImageData -Creates an **ImageData** object based on the width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------- | -| sw | number | Yes | 0 | Width of the **ImageData** object.| -| sh | number | Yes | 0 | Height of the **ImageData** object.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ------------- | +| sw | number | Yes | 0 | Width of the **ImageData** object.| +| sh | number | Yes | 0 | Height of the **ImageData** object.| -### createImageData - createImageData(imageData: ImageData): ImageData -Creates an **ImageData** object based on the given existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). +Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy.| +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object to copy.| **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2003,29 +2175,29 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| sx | number | Yes| 0 | X-coordinate of the upper left corner of the output area.| -| sy | number | Yes| 0 | Y-coordinate of the upper left corner of the output area.| -| sw | number | Yes| 0 | Width of the output area.| -| sh | number | Yes| 0 | Height of the output area.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | --------------- | +| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| +| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| +| sw | number | Yes | 0 | Width of the output area. | +| sh | number | Yes | 0 | Height of the output area. | **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| +| Type | Description | +| ---------------------------------------- | ------------ | +| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.| ### getImageData getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. +Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | --------------- | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| @@ -2034,9 +2206,44 @@ Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created **Return value** -| Type | Description | -| ---------- | ---------------------------------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.| +| Type | Description | +| ---------------------------------------- | ------------- | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| + + +**Example** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.drawImage(this.img,0,0,130,130); + var imagedata = this.offContext.getImageData(50,50,130,130); + this.offContext.putImageData(imagedata,150,150); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ### putImageData @@ -2045,11 +2252,11 @@ putImageData(imageData: Object, dx: number, dy: number): void putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void -Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas. +Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. **Parameters** -| Parameters | Type | Mandatory | Default Value | Description | +| Name | Type | Mandatory | Default Value | Description | | ----------- | ------ | ---- | ------------ | ----------------------------- | | imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | @@ -2104,8 +2311,8 @@ Sets the dash line style. **Parameters** -| Parameter | Type | Description | -| -------- | ----- | -------------------- | +| Name | Type | Description | +| -------- | -------- | ------------------- | | segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.| **Example** @@ -2137,7 +2344,7 @@ struct SetLineDash { } } ``` - ![zh-cn_image_000000127777772](figures/zh-cn_image_000000127777772.png) + ![en-us_image_000000127777772](figures/en-us_image_000000127777772.png) ### getLineDash @@ -2148,29 +2355,37 @@ Obtains the dash line style. **Return value** -| Type | Description | -| ----- | ------------------------ | +| Type | Description | +| -------- | ------------------------ | | number[] | An array describing the interval of alternate line segments and length of spacing.| **Example** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { +@Entry +@Component +struct OffscreenCanvasGetLineDash { + @State message: string = 'Hello World' private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.offContext.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) this.offContext.stroke(); @@ -2180,53 +2395,14 @@ Obtains the dash line style. }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![en-us_image_000000127777778](figures/en-us_image_000000127777778.png) -### transferFromImageBitmap - -transferFromImageBitmap(bitmap: ImageBitmap): void - -Displays the specified **ImageBitmap** object. - -**Parameters** - -| Parameters | Type | Description | -| ------ | ----------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') - } - } - ``` - ![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png) ### toDataURL @@ -2250,7 +2426,7 @@ Generates a URL containing image display information. **Example** ```ts - // xxx.ets +// xxx.ets @Entry @Component struct ToDataURL { @@ -2275,6 +2451,19 @@ struct ToDataURL { ``` +### imageSmoothingQuality + +imageSmoothingQuality(quality: imageSmoothingQuality) + +Sets the quality of image smoothing. This API is a void API. + + **Parameters** + +| Name | Type | Description | +| ------- | --------------------- | ---------------------------------------- | +| quality | imageSmoothingQuality | Quality of image smoothing. The value can be **'low'**, **'medium'**,or **'high'**.| + + ### transferToImageBitmap transferToImageBitmap(): ImageBitmap @@ -2285,7 +2474,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O | Type | Description | | ---------------------------------------- | --------------- | -| [ImageData](ts-components-canvas-imagebitmap.md)| Pixel data rendered on the **OffscreenCanvas**.| +| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.| **Example** @@ -2294,10 +2483,11 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O // xxx.ets @Entry @Component - struct CanvasExample { + struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2305,7 +2495,14 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.restore() + var imageData = this.offContext.createImageData(100, 100) + for (var i = 0; i < imageData.data.length; i += 4) { + imageData.data[i + 0] = 255 + imageData.data[i + 1] = 0 + imageData.data[i + 2] = 255 + imageData.data[i + 3] = 255 + } + this.offContext.putImageData(imageData, 10, 10) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2315,6 +2512,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O } } ``` +![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png) ### restore @@ -2326,29 +2524,35 @@ Restores the saved drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.restore() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### save @@ -2361,29 +2565,35 @@ Saves the current drawing context. ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.save() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) }) - } - .width('100%') - .height('100%') } + .width('100%') + .height('100%') } +} ``` +![en-us_image_000000127777781](figures/en-us_image_000000127777781.png) ### createLinearGradient diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 982ea614f7560050b2993cccacb67a841cbf26bd..2c8ba7c33a29b398ae2144c6435fe0d6a10671a6 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -11,7 +11,7 @@ The area change event is triggered when the component's size, position, or any o | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| onAreaChange(event: (oldValue: Area, newValue: Area) => void) | No | Triggered when the component area changes. For details about the **Area** type, see [Area](ts-types.md#area8).| +| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) => void) | No | Triggered when the component area changes.| ## Example @@ -22,7 +22,7 @@ The area change event is triggered when the component's size, position, or any o @Component struct AreaExample { @State value: string = 'Text' - @State size1: string = '' + @State sizeValue: string = '' build() { Column() { @@ -33,9 +33,9 @@ struct AreaExample { }) .onAreaChange((oldValue: Area, newValue: Area) => { console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) - this.size1 = JSON.stringify(newValue) + this.sizeValue = JSON.stringify(newValue) }) - Text('new area is: \n' + this.size).margin({ right: 30, left: 30 }) + Text('new area is: \n' + this.sizeValue).margin({ right: 30, left: 30 }) } .width('100%').height('100%').margin({ top: 30 }) } diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md index 2b4efca72f4786729d4f11234febd406778bc266..e4838da489a5d5bb3ac3651885c9d456ed7322eb 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -11,49 +11,11 @@ - [Resource File Categories](ui-ts-basic-resource-file-categories.md) - [Resource Access](ts-resource-access.md) - [Pixel Units](ts-pixel-units.md) - - Declarative Syntax - - [About Usage of UI Description Specifications](ts-syntax-intro.md) - - About General UI Description Specifications - - [Basic Concepts](ts-general-ui-concepts.md) - - Declarative UI Description Specifications - - [Configuration Without Parameters](ts-parameterless-configuration.md) - - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) - - [Attribute Configuration](ts-attribution-configuration.md) - - [Event Configuration](ts-event-configuration.md) - - [Child Component Configuration](ts-child-component-configuration.md) - - Componentization - - [@Component](ts-component-based-component.md) - - [@Entry](ts-component-based-entry.md) - - [@Preview](ts-component-based-preview.md) - - [@Builder](ts-component-based-builder.md) - - [@Extend](ts-component-based-extend.md) - - [@CustomDialog](ts-component-based-customdialog.md) - - [@Styles](ts-component-based-styles.md) - - About UI State Management - - [Basic Concepts](ts-ui-state-mgmt-concepts.md) - - Managing Component States - - [@State](ts-component-states-state.md) - - [@Prop](ts-component-states-prop.md) - - [@Link](ts-component-states-link.md) - - Managing Application States - - [AppStorage](ts-application-states-appstorage.md) - - [LocalStorage](ui-ts-local-storage.md) - - [PersistentStorage](ts-application-states-apis-persistentstorage.md) - - [Environment](ts-application-states-apis-environment.md) - - Managing Other States - - [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md) - - [@Consume and @Provide](ts-other-states-consume-provide.md) - - [@Watch](ts-other-states-watch.md) - - Rendering Control Syntax - - [if/else](ts-rending-control-syntax-if-else.md) - - [ForEach](ts-rending-control-syntax-foreach.md) - - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) - - About Componentization - - [build Function](ts-function-build.md) + + - Componentization - [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md) - [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md) - - [Examples: Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - - [About Syntactic Sugar](ts-syntactic-sugar.md) + - [Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - Common Component Development Guidelines - [Button](ui-ts-basic-components-button.md) - [Web](ui-ts-components-web.md) diff --git a/en/application-dev/ui/arkui-overview.md b/en/application-dev/ui/arkui-overview.md index 43bff6f16355673a8bc4b027680e427b9801d4d3..5859e248d019b64d8e78886d8d4b5c518acf39b9 100644 --- a/en/application-dev/ui/arkui-overview.md +++ b/en/application-dev/ui/arkui-overview.md @@ -21,7 +21,7 @@ ArkUI is a UI development framework that provides what you'll need to develop ap - Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts. - Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability. - Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style. -- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. +- Two development paradigms: ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice. | Development Paradigm | Description | Applicable To | Intended Audience | | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/ui/ts-application-states-apis-environment.md b/en/application-dev/ui/ts-application-states-apis-environment.md deleted file mode 100644 index 9da95fc0b83e5cb259e2233275075f734252e953..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-environment.md +++ /dev/null @@ -1,34 +0,0 @@ -# Environment - - -Environment is a singleton object created by the framework when the application is started. It provides the AppStorage with a series of environment state attributes required by the application. These attributes describe the device environment where the application runs. Environment and its attributes are immutable, and all attribute values are of the simple type. The following example shows how to obtain the semantic environment from Environment: - - -```ts -Environment.EnvProp("accessibilityEnabled", "default"); -var enable = AppStorage.Get("accessibilityEnabled"); -``` - - -accessibilityEnabled is the default system variable identifier provided by Environment. You need to bind the corresponding system attribute to the AppStorage. Then, you can use the methods or decorators in the AppStorage to access the corresponding system attribute data. - - -## Environment APIs - -| key | Parameter | Return Value | Description | -| -------- | -------- | -------- | -------- | -| EnvProp | key: string,
defaultValue: any | boolean | Binds this system attribute to the AppStorage. You are advised to use this API during application startup. If the attribute already exists in the AppStorage, false is returned. Do not use the variables in the AppStorage. Instead, call this method to bind environment variables. | -| EnvProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates this system item array with the AppStorage. | -| Keys | Array<string> | number | Returns the associated system item array. | - - -## Built-in Environment Variables - -| key | Type | Description | -| -------- | -------- | -------- | -| accessibilityEnabled | boolean | Whether to enable accessibility. | -| colorMode | ColorMode | Color mode. The options are as follows:
- **ColorMode.LIGHT**: light mode.
- **ColorMode.DARK**: dark mode. | -| fontScale | number | Font scale. The value range is [0.85, 1.45]. | -| fontWeightScale | number | Font weight scale. The value range is [0.6, 1.6]. | -| layoutDirection | LayoutDirection | Layout direction. The options are as follows:
- **LayoutDirection.LTR**: The direction is from left to right.
- **LayoutDirection.RTL**: The direction is from right to left. | -| languageCode | string | Current system language. The value is in lowercase, for example, zh. | diff --git a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md b/en/application-dev/ui/ts-application-states-apis-persistentstorage.md deleted file mode 100644 index 8df5e76e2855c5f5d211aa35d87f54d19f5ce352..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-apis-persistentstorage.md +++ /dev/null @@ -1,48 +0,0 @@ -# PersistentStorage - - -ArkUI provides some static methods in the PersistentStorage class for managing persistent data of applications. Persistent data with specific tags can be linked to the AppStorage, and then the persistent data can be accessed through the AppStorage APIs. Alternatively, the @StorageLink decorator can be used to access the variable of the specific key. - - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| PersistProp | key : string
defaultValue: T | void | Changes the associated named attribute to persistent data in the AppStorage. The value overwriting sequence is as follows:
- If the attribute exists in the AppStorage, use it to overwrite the value in Persistent.
- If Persistent contains the specified attribute, use the attribute value in Persistent.
- If the preceding conditions are not met, use defaultValue. The values null and undefined are not supported. | -| DeleteProp | key: string | void | Cancels two-way binding. The value of this attribute will be deleted from the persistent storage. | -| PersistProps | keys: {
key: string,
defaultValue: any
}[] | void | Associates multiple named attribute bindings. | -| Keys | void | Array <string> | Returns the flags of all persistent attributes. | - - -> **NOTE** -> -> - When using **PersistProp**, ensure that the input key exists in the AppStorage. -> -> - **DeleteProp** takes effect only for the data that has been linked during the current startup. - - -```ts -// xxx.ets -PersistentStorage.PersistProp("highScore", "0"); - -@Entry -@Component -struct PersistentComponent { - @StorageLink('highScore') highScore: string = '0' - @State currentScore: number = 0 - build() { - Column() { - if (this.currentScore === Number(this.highScore)) { - Text(`new highScore : ${this.highScore}`) - } - Button() { - Text(`goal!, currentScore : ${this.currentScore}`) - .fontSize(10) - }.onClick(() => { - this.currentScore++ - if (this.currentScore > Number(this.highScore)) { - this.highScore = this.currentScore.toString() - } - }) - } - } -} -``` diff --git a/en/application-dev/ui/ts-application-states-appstorage.md b/en/application-dev/ui/ts-application-states-appstorage.md deleted file mode 100644 index 5877f75ca55ad03cafb78eda50c0b26475f3033e..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-application-states-appstorage.md +++ /dev/null @@ -1,89 +0,0 @@ -# AppStorage - - -AppStorage is a singleton object in an application, which is created by the UI framework when the application is started and destroyed when the application exits. It is used to provide central storage for changing state attributes of an application. AppStorage contains all the state attributes that need to be accessed throughout the application. The AppStorage retains all attributes and their values as long as the application remains running, and the attribute values can be accessed through unique key values. - - -The UI component can synchronize the application state data with the AppStorage through the decorators. The application service logic can also be implemented by accessing the AppStorage through APIs. - - -The selection state attribute of the AppStorage can be synchronized with different data sources or data sinks. These data sources and data sinks can be local or remote devices and provide different functions, such as data persistence. Such data sources and data sinks can be implemented independently of the UI in the service logic. - - -By default, the attributes in the AppStorage are changeable. If needed, AppStorage can also use immutable (read-only) attributes. - - -## AppStorage APIs - -| Name | Type | Return Value | Definition | -| -------- | -------- | -------- | -------- | -| SetAndLink | key: string,
defaultValue: T | @Link | Works in a way similar to the Link API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Link instance corresponding to the default value is created and returned. | -| Set | key: string,
newValue: T | void | Replaces the value of a saved key. | -| Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. | -| SetAndProp | propName: string,
defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. | -| Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.
**NOTE**
The attribute value used in the prop method must be of a simple type. | -| SetOrCreate | key: string,
newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.
If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. | -| Get | key: string | T or undefined | Obtains the value of the specified key. | -| Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. | -| Keys | void | array<string> | Returns an array of strings containing all keys. | -| Delete | key: string | boolean | Deletes the key-value pair for the specified key. Returns true if the key-value pair exists and is successfully deleted; returns false otherwise. | -| Clear | void | boolean | Deletes all attributes. If any of the attributes is being referenced by a state variable, false is returned. | -| IsMutable | key: string | boolean | Specifies whether the attribute exists and can be changed. | - - -## Synchronization Between AppStorage and Components - -In [Managing Component States](ts-component-states-state.md), we have defined how to synchronize the state variables of child components with the @State decorated variables in the parent component or ancestor component, including @Prop, @Link, and @Consume. - -In this section, we'll describe how to synchronize component variables with the AppStorage through the @StorageLink and @StorageProp decorators. - - -### @StorageLink Decorator - -Two-way data binding can be established between components and the AppStorage through state variables decorated by @StorageLink(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageLink decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to this variable in the component will be first synchronized to the AppStorage, and then to other bound instances, such as PersistentStorage or other bound UI components. - - -### @StorageProp Decorator - -One-way data binding can be established between components and the AppStorage through state variables decorated by @StorageProp(_key_). Wherein, key is the attribute key value in the AppStorage. When a component containing the @StorageProp decorated variable is created, the variable is initialized using the value in the AppStorage. Changes made to the value in the AppStorage will cause the bound UI component to update the state. - - -## Example - - -```ts -// xxx.ets - -@Entry -@Component -struct ComponentA { - @StorageLink('varA') varA: number = 2 - @StorageProp('languageCode') lang: string = 'en' - private label: string = 'count' - - aboutToAppear() { - this.label = (this.lang === 'en') ? 'Number' : 'Count' - } - - build() { - Row({ space: 20 }) { - - Button(`${this.label}: ${this.varA}`) - .onClick(() => { - AppStorage.Set('varA', AppStorage.Get('varA') + 1) - }) - Button(`lang: ${this.lang}`) - .onClick(() => { - if (this.lang === 'zh') { - AppStorage.Set('languageCode', 'en') - } else { - AppStorage.Set('languageCode', 'en') - } - this.label = (this.lang === 'en') ? 'Number' : 'Count' - }) - } - } -} -``` - -Each time the user clicks the **Count** button, the value of **this.varA** will increase by 1. This variable is synchronized with varA in the AppStorage. Each time the user clicks the language icon, the value of **languageCode** in the AppStorage will be changed, and the change will be synchronized to the **this.lang** variable. diff --git a/en/application-dev/ui/ts-attribution-configuration.md b/en/application-dev/ui/ts-attribution-configuration.md deleted file mode 100644 index 70d85aff0d3bb3a9b418753655ea33480bf681ff..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-attribution-configuration.md +++ /dev/null @@ -1,44 +0,0 @@ -# Attribute Configuration - - -Use attribute methods to configure component attributes. An attribute method follows the corresponding component and is bound to the component using the "." operator. - - -- The following is an example of configuring the font size attribute of the Text component: - - ```ts - Text('123') - .fontSize(12) - ``` - - -- Use the "." operator to implement chain call to configure multiple attributes at the same time, as shown below: - - ```ts - Image('a.jpg') - .alt('error.jpg') - .width(100) - .height(100) - ``` - - -- In addition to constants, you can also pass variables or expressions, as shown below: - - ```ts - // Size, count, and offset are private variables defined in the component. - Text('hello') - .fontSize(this.size) - Image('a.jpg') - .width(this.count % 2 === 0 ? 100 : 200) - .height(this.offset + 100) - ``` - - -- For attributes of preset components, the framework also provides some predefined enumeration types, which you can pass as parameters to methods. Enumeration types must meet the parameter type requirements on the enumeration type definitions for specific attributes. You can configure the font color and weight attributes of the Text component as follows: - - ```ts - Text('hello') - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(FontWeight.Bold) - ``` diff --git a/en/application-dev/ui/ts-child-component-configuration.md b/en/application-dev/ui/ts-child-component-configuration.md deleted file mode 100644 index c2fe0c68c3b49e09091be56505cae0bea9e370fb..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-child-component-configuration.md +++ /dev/null @@ -1,49 +0,0 @@ -# Child Component Configuration - - -For a component that supports child components, for example, a container component, add the UI descriptions of the child components inside "{ ... }". The **\**, **\**, **\**, **\ - - ``` + .height('100%') + } +} +``` ## 相关实例 diff --git a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md index d31a74e423230d965ccda41153480ae2348f945f..a7da0fe1e9b46e5ccb379677a57e0da65cad36f7 100644 --- a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md +++ b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-overview.md @@ -1,3 +1,12 @@ # 后台代理提醒概述 -开发者在应用开发时,可以调用后台代理提醒类ReminderRequest去创建定时提醒,包括倒计时、日历、闹钟三种提醒类型。使用后台代理提醒能力后,应用可以被冻结或退出,计时和弹出提醒的功能将被后台系统服务代理。 +OpenHarmony设计了相关的后台活动规范。三方应用退后台后如果没有执行相关的后台任务,会被挂起。而对于某些应用,可能需要在某些指定的时刻,处理一些工作。如购物类应用,可能需要在某些时间点,提醒用户有抢购活动可以参加。此类功能通常的实现是应用使用定时器,在时间达到后,由系统拉起应用,执行相关的任务。但是给应用开放了定时器的功能,可能会造成这个机制被滥用,导致后台被挂起的应用频繁地用定时器唤醒。为了避免恶意的后台活动,同时满足应用的业务诉求,设计了后台代理提醒功能。 +开发者在应用开发时,使用后台代理提醒能力后,应用可以被挂起或退出,计时和弹出提醒的功能将被后台系统服务代理。避免的应用被频繁唤醒的问题,有助于降低功耗。 + +## 提醒实例类型 + +- **倒计时类型**:基于倒计时的提醒功能,适用于短时的计时提醒业务。 + +- **日历类型**:基于日历的提醒功能,适用于较长时间的提醒业务。 + +- **闹钟类型**:基于时钟的提醒功能,应用可以使用此功能,实现闹钟相关的业务。 diff --git a/zh-cn/application-dev/task-management/background-task-overview.md b/zh-cn/application-dev/task-management/background-task-overview.md index a045739051f012c791ca6b093c0afc362ebd7749..c24d818516a8d473bca665304c4d8851f2b531f2 100644 --- a/zh-cn/application-dev/task-management/background-task-overview.md +++ b/zh-cn/application-dev/task-management/background-task-overview.md @@ -1,26 +1,32 @@ # 后台任务概述 -后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。同时,应用可以申请能效资源,保证自己在一段时间内不会被挂起,或者在挂起状态能够正常使用一些资源,例如公共事件、计时器等。 +后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。 +针对应用或业务模块处于后台(无可见界面)时,有需要继续执行或者后续执行的业务,可基于业务类型,申请[短时任务](#短时任务)延迟挂起或者[长时任务](#长时任务)避免进入挂起状态;使用[延迟调度任务](#延迟任务),执行对实时性要求不高的任务;同时针对特权应用,如果需要更加灵活的配置,可以申请[能效资源](#申请能效资源)。 ## 后台任务类型 -本文描述的后台任务特指应用或业务模块处于后台(无可见界面)时,有需要继续执行或者后续执行的业务。OpenHarmony将后台任务分为三种类型,并执行不同的处理: +OpenHarmony将后台任务分为四种类型,并提供了一个资源申请的扩展功能: - **1. 无后台业务** :应用或业务模块退到后台后,无任务需要处理。 + **无后台业务** :应用或业务模块退到后台后,无任务需要处理。 - **2. 短时任务** :应用或业务模块退到后台后,如果有紧急不可推迟且短时间能完成的任务,如应用退后台要进行数据压缩,不可中断,则使用短时任务申请延迟进入挂起(Suspend)状态。 + **短时任务** :应用或业务模块退到后台后,如果有紧急不可推迟且短时间能完成的任务,如应用退后台要进行数据压缩,不可中断,则使用短时任务申请延迟进入挂起(Suspend)状态。 - **3. 长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 + **长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 - **4. 能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。 + **延迟任务** :延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性不高的任务。当满足设定条件的时候,任务会被放入待调度队列,当系统空闲时调度该任务。 + **能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。 + +## 最佳后台任务选择 + +![后台任务选择](public_sys-resources/bgtask_choice.png) ## 短时任务 退到后台的应用有不可中断且短时间能完成的任务时,可以使用短时任务机制。该机制允许应用在后台短时间内完成任务,保障应用业务运行不受后台生命周期管理的影响。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** > 短时任务仅针对应用的临时任务提供资源使用生命周期保障,限制单次最大使用时长为3分钟,全天使用配额默认为10分钟(具体时长系统根据应用场景和系统状态智能调整)。 @@ -63,9 +69,44 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 - 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 - 一个Ability同一时刻只能申请运行一个长时任务。 -## 能效资源申请 -能效资源可以分为四种,CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLOOTOOTH,AUDIO)。 -应用或进程申请能效资源后能够获得相应特权,例如:申请CPU资源后可以不被挂起;申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加;申请软件、硬件资源后,相关资源在挂起状态下不被代理。 +## 延迟任务 +延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性要求不高的任务,比如设备空闲时候做一次数据学习等场景。当应用申请延迟任务的时候,任务会被放入待调度队列,系统会根据当前状态,如内存、功耗、温度等统一决策最优的调度时机。同时支持任务的持久化,应用退出或者设备重启,设置的任务同样能够被触发。 + +### 延迟任务调度约束 + +延迟调度任务的使用需要遵从如下约束和规则: + +- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[申请能效资源](efficiency-resources-apply-dev-guide.md)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。 +- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。 + + | 应用分组 | 延迟任务执行频率约束 | + | --------------------|------------------------- | + | 活跃 | 最小间隔2小时 | + | 每日使用 | 最小间隔4小时 | + | 经常使用 | 最小间隔24小时 | + | 不经常使用 | 最小间隔48小时 | + | 受限分组 | 禁止 | + | 未使用分组 | 禁止 | + | [能效资源豁免分组](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | 执行频率不受限制 | + +- **WorkInfo设置参数约束** + + - workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 + + - 至少要设置一个满足的条件。 + + - 重复任务时间间隔至少20分钟,当设置重复任务时间间隔时,必须设置始终重复和重复次数中的一个。 + + - 携带参数信息支持number、string、bool三种类型。 + +## 申请能效资源 +能效资源可以分为四种:CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLUETOOTH,AUDIO)。 + +应用或进程申请能效资源后能够获得相应特权: + * 申请CPU资源后可以不被挂起,直到任务完成。 + * 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加 + * 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务、 + * 申请硬件资源后,应用在后台被挂起后,依然能够被相关服务唤醒,执行相应的任务。 **表1** 能效资源种类 @@ -84,3 +125,4 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 - 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。 - 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。 - WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。 +- 需要使用能效资源的应用,需要向应用中心提出申请,获取相应的特权。 diff --git a/zh-cn/application-dev/task-management/background-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md similarity index 50% rename from zh-cn/application-dev/task-management/background-task-dev-guide.md rename to zh-cn/application-dev/task-management/continuous-task-dev-guide.md index fd4d3c3948b6ed69680c9294b10bb1838654b35f..15a57a485a12c2048f55a2dc10cffc8abe1c9f9b 100644 --- a/zh-cn/application-dev/task-management/background-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md @@ -1,89 +1,9 @@ -# 后台任务开发指导 - -## 场景介绍 - -应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。如果应用需要更加灵活的配置,可以申请能效资源。常见的使用能效资源的场景有:1.应用保证自己在一个时间段内不被挂起,直到任务完成;2.应用处于挂起状态时仍然需要系统的资源,例如闹钟需要计时器资源;3.延时任务需要不受到执行频率的限制,并且拥有更长的执行时间。 - -在挂起时如果需要单独的某种资源不被代理或者需要更长的延时任务执行时间,可以申请所需的能效资源。 - -## 短时任务 - -### 接口说明 - -**表1** 短时任务主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为180000,低电量时默认值为60000。 | -| getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | -| cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | - - -### 开发步骤 - - -1. 申请延迟挂起 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - let myReason = 'test requestSuspendDelay'; - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); - }); - - var id = delayInfo.requestId; - console.info("requestId is: " + id); - ``` - - -2. 获取进入挂起前的剩余时间 - - ```js - backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); - }); - ``` - - -3. 取消延迟挂起 - - ```js - backgroundTaskManager.cancelSuspendDelay(id); - ``` - - -### 开发实例 +## 长时任务 -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; -let myReason = 'test requestSuspendDelay'; - -// 申请延迟挂起 -let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); -}); - -// 打印延迟挂起信息 -var id = delayInfo.requestId; -var time = delayInfo.actualDelayTime; -console.info("The requestId is: " + id); -console.info("The actualDelayTime is: " + time); - -// 获取应用程序进入挂起状态前的剩余时间 -backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); -}).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); -}); - -// 取消延迟挂起 -backgroundTaskManager.cancelSuspendDelay(id); -``` +### 场景说明 -## 长时任务 +如果应用需要在后台长时间执行用户可感知的任务,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 +长时任务在后台执行没有时间限制。为了避免该机制被滥用,系统只允许申请有限个数的长时任务类型,同时会有相应的通知提示与长时任务相关联,使用户可感知,并且系统会添加相应的校验机制,确保应用是的确在执行相应的长时任务。 ### 权限 @@ -120,146 +40,35 @@ ohos.permission.KEEP_BACKGROUND_RUNNING 基于FA模型: -1. 新建Api Version 8的工程后,在工程目录中右键选择“new” -> “Ability” -> “Service Ability” 快速创建Service Ability组件。并在config.json文件中配置长时任务权限、后台模式类型,其中Ability类型为“service”。 - - ``` - "module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // 后台模式类型 - "type": "service" // ability类型为service - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 - } - ] - } - ``` - -2. 申请长时任务。 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import featureAbility from '@ohos.ability.featureAbility'; - import wantAgent from '@ohos.wantAgent'; - - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - ``` - -3. 停止长时任务。 - - ```js - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import featureAbility from '@ohos.ability.featureAbility'; - - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); +基于FA的Service Ability使用,参考[ServiceAbility开发指导](../ability/fa-serviceability.md)。 - ``` +当不需要与后台执行的长时任务交互时,可以采用startAbility()方法启动Service Ability。并在Service Ability的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。当任务执行完,再调用长时任务取消接口,及时释放资源。 -基于Stage模型: +当需要与后台执行的长时任务交互时(如播放音乐等)。可以采用connectAbility()方法启动并连接Service Ability。在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 -1. 新建Api Version 9的工程后,在工程目录中右键选择“New” -> “Ability” 快速创建Ability组件。并在module.json5文件中配置长时任务权限、后台模式类型。 +1、新建Api Version 8的工程后,在工程目录中右键选择“new” -> “Ability” -> “Service Ability” 快速创建Service Ability组件。并在config.json文件中配置长时任务权限、后台模式类型,其中Ability类型为“service”。 - ``` - "module": { - "abilities": [ +``` +"module": { + "package": "com.example.myapplication", + "abilities": [ { - "backgroundModes": [ + "backgroundModes": [ "dataTransfer", "location" - ], // 后台模式类型 + ], // 后台模式类型 + "type": "service" // ability类型为service } - ], - "requestPermissions": [ + ], + "reqPermissions": [ { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 } - ] - } - ``` - -2. 申请长时任务。 - - ```ts - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - import wantAgent from '@ohos.wantAgent'; - - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - ``` - -3. 停止长时任务。 - - ```ts - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - - ``` - - -### 开发实例 - -基于FA模型: - -基于FA的Service Ability使用,参考[ServiceAbility开发指导](../ability/fa-serviceability.md)。 - -当不需要与后台执行的长时任务交互时,可以采用startAbility()方法启动Service Ability。并在Service Ability的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。当任务执行完,再调用长时任务取消接口,及时释放资源。 + ] +} +``` -当需要与后台执行的长时任务交互时(如播放音乐等)。可以采用connectAbility()方法启动并连接Service Ability。在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 +2、在Service Ability调用长时任务的申请和取消接口。 ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; @@ -367,13 +176,117 @@ export default { 基于Stage模型: Stage模型的相关信息参考[Stage模型综述](../ability/stage-brief.md)。 -当应用需要在后台执行长时任务时,可以通过Call的方式在后台创建并运行Ability。使用方式参考[Call调用开发指导](../ability/stage-call.md)。 + +1、新建Api Version 9的工程后,在工程目录中右键选择“New” -> “Ability” 快速创建Ability组件。并在module.json5文件中配置长时任务权限、后台模式类型。 + +``` +"module": { + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // 后台模式类型 + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 + } + ] +} +``` + +2、在应用内执行长时任务时,由于元能力启动管控规则限制,不支持同应用通过startAbilityByCall的形式在后台创建并运行Ability。可以直接在page中,执行相应的代码。Stage模型的Ability使用参考[Ability开发指导](../ability/stage-ability.md)。 + +```ts +import wantAgent from '@ohos.wantAgent'; +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +@Entry +@Component +struct Index { + @State message: string = 'test' + // 通过getContext方法,来获取page所在的Ability上下文。 + private context: any = getContext(this) + + startContinuousTask() { + let wantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); + } + + stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } + + build() { + Row() { + Column() { + Text("Index") + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button() { Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // 通过按钮申请长时任务 + this.startContinuousTask(); + + // 此处执行具体的长时任务逻辑,如放音等。 + }) + + Button() { Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) + .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) + .onClick(() => { + // 此处结束具体的长时任务的执行 + + // 通过按钮取消长时任务 + this.stopContinuousTask(); + }) + } + .width('100%') + } + .height('100%') + } +} +``` + +3、当需要跨设备或者跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行Ability。使用方式参考[Call调用开发指导](../ability/stage-call.md)。 ```ts import Ability from '@ohos.application.Ability' import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; +const MSG_SEND_METHOD: string = 'CallSendMsg' + let mContext = null; function startContinuousTask() { @@ -382,7 +295,7 @@ function startContinuousTask() { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", } ], // 点击通知后,动作类型 @@ -436,15 +349,16 @@ class MySequenceable { function sendMsgCallback(data) { console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new Mysequenceable(0, "") + let receivedData = new MySequenceable(0, "") data.readSequenceable(receivedData) console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 if (receivedData.str === 'start_bgtask') { startContinuousTask() } else if (receivedData.str === 'stop_bgtask') { stopContinuousTask(); } - return new Mysequenceable(10, "Callee test"); + return new MySequenceable(10, "Callee test"); } export default class BgTaskAbility extends Ability { @@ -467,7 +381,7 @@ export default class BgTaskAbility extends Ability { onWindowStageCreate(windowStage) { console.info("[Demo] BgTaskAbility onWindowStageCreate") - windowStage.loadContent("pages/second").then((data)=> { + windowStage.loadContent("pages/index").then((data)=> { console.info(`load content succeed with data ${JSON.stringify(data)}`) }).catch((error)=>{ console.error(`load content failed with error ${JSON.stringify(error)}`) @@ -488,93 +402,6 @@ export default class BgTaskAbility extends Ability { }; ``` -## 能效资源申请 - -### 接口说明 - -**表1** 能效资源申请主要接口 - -| 接口名 | 描述 | -| ---------------------------------------- | ---------------------------------------- | -| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | 申请能效资源。 | -| resetAllEfficiencyResources():void | 释放申请的能效资源。 | - - -### 开发步骤 - - -1. 申请能效资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -let request = { - resourceTypes: backgroundTaskManager.ResourceType.CPU, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); -``` - -2. 释放申请的部分资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -let request = { - resourceTypes: backgroundTaskManager.ResourceType.CPU, - isApply: false, - timeOut: 0, - reason: "reset", -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); -``` - -3. 释放申请的所有资源 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); -``` - -### 开发实例 - -```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; - -// 申请能效资源 -let request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | - backgroundTaskManager.ResourceType.TIMER, - isApply: true, - timeOut: 0, - reason: "apply", - isPersist: true, - isProcess: true, -}; -let res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); - -// 释放部分资源 -request = { - resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, - isApply: false, - timeOut: 0, - reason: "reset", -}; -res = backgroundTaskManager.applyEfficiencyResources(request); -console.info("the result of request is: " + res); - -// 释放全部资源 -backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); -``` - ## 相关实例 基于后台任务管理,有以下相关实例可供参考: diff --git a/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..ebdd94a0c1a20876b854d16a19725ad854c773f2 --- /dev/null +++ b/zh-cn/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -0,0 +1,53 @@ +## 申请能效资源 + +### 场景说明 + +在实际的系统中,存在一些重要性高的系统应用,虽然此类应用相比普通应用具有一定的特权,但为了进一步平衡系统的功耗开销,这些应用同样需要支持在后台可被挂起。但对于系统特权应用,为了避免挂起后重要功能受到影响,提供了独立的能效资源申请接口,使这些特权应用可以在后台执行一些特殊的任务和使用特定的系统资源,例如在被挂起期间如果仍然希望能够收到系统公共事件,可以使用能效资源接口向系统申请使用公共事件资源。 + +对于需要升级为特权应用的,开发者需要合理评估自己的业务诉求,向应用中心提出申请。 + +### 接口说明 + +**表1** 申请能效资源主要接口 + +| 接口名 | 描述 | +| ---------------------------------------- | ---------------------------------------- | +| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | 申请能效资源。 | +| resetAllEfficiencyResources():void | 释放申请的能效资源。 | + + +### 开发步骤 + +1、当特权应用需要在后台使用特殊资源时。向系统申请目标资源。 + +2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。 + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +// 申请能效资源 +let request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT | + backgroundTaskManager.ResourceType.TIMER, + isApply: true, + timeOut: 0, + reason: "apply", + isPersist: true, + isProcess: true, +}; +let res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// 释放部分资源 +request = { + resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT, + isApply: false, + timeOut: 0, + reason: "reset", +}; +res = backgroundTaskManager.applyEfficiencyResources(request); +console.info("the result of request is: " + res); + +// 释放全部资源 +backgroundTaskManager.resetAllEfficiencyResources(); +``` diff --git a/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png b/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png new file mode 100644 index 0000000000000000000000000000000000000000..4f1fd6eefab0302ba4f936828adefbedf8f6c1f8 Binary files /dev/null and b/zh-cn/application-dev/task-management/public_sys-resources/bgtask_choice.png differ diff --git a/zh-cn/application-dev/task-management/transient-task-dev-guide.md b/zh-cn/application-dev/task-management/transient-task-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d27a88e576e312626e1c810ab9b90253b1223408 --- /dev/null +++ b/zh-cn/application-dev/task-management/transient-task-dev-guide.md @@ -0,0 +1,84 @@ +## 短时任务 + +### 场景说明 + +当应用退到后台默认有6到12秒的运行时长,超过该时间后,系统会将应用置为挂起状态。对于绝大多数应用,6到12秒的时间,足够执行一些重要的任务,但如果应用需要更多的时间,可以通过短时任务接口,扩展应用的执行时间。 +建议不要等到应用退后台后,才调用requestSuspendDelay方法申请延迟挂起,而是应该在执行任何的耗时操作前,都应该调用该接口,向系统申明扩展应用的执行时间。 +当应用在前台时,使用requestSuspendDelay方法,不会影响应用的短时任务配额。 + +由于每个应用每天的短时任务配额时间有限,当执行完耗时任务后,应当及时取消延迟挂起的申请。 + +一些典型的耗时任务有,需要保存一些状态数据到本地数据库,需要打开和处理一个大型文件,需要同步一些数据到应用的云端服务器等。 + + +### 接口说明 + + +**表1** 短时任务主要接口 + +| 接口名 | 描述 | +| ---------------------------------------- | ---------------------------------------- | +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为180000,低电量时默认值为60000。 | +| getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | +| cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | + + +### 开发步骤 + +1、当应用需要开始执行一个耗时的任务时。调用短时任务申请接口,并且在任务执行完后,调用短时任务取消接口。 + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +let delayInfo; +let id; + +// 申请延迟挂起 +function requestSuspendDelay() { + let myReason = 'test requestSuspendDelay'; + delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + // 此回调函数执行,表示应用的延迟挂起申请即将超时,应用需要执行一些清理和标注工作。 + }); + + id = delayInfo.requestId; + console.info("requestId is: " + id); +} + +// 获取进入挂起前的剩余时间 +function getRemainingDelayTime() { + let delayTime = 0; + backgroundTaskManager.getRemainingDelayTime(id).then((res) => { + console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); + delayTime = res; + }).catch((err) => { + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); + }); + return delayTime; +} + +// 取消延迟挂起 +function cancelSuspendDelay() { + backgroundTaskManager.cancelSuspendDelay(id); +} + +function performingLongRunningTask() { + // 在执行具体的耗时任务前,调用短时任务申请接口。向系统申请延迟挂起,延长应用的后台执行时间。 + requestSuspendDelay(); + + // 通过剩余时间查询接口,获取可用时间配额。 + let delayTime = getRemainingDelayTime(); + + if (delayTime < 0) { // 如果时间配置少于一定的大小,考虑取消此次耗时操作。 + // 处理短时任务配额时间不够的场景 + + cancelSuspendDelay(); + return; + } + + // 此处执行具体的耗时任务。 + + // 耗时任务执行完,调用短时任务取消接口,避免配额浪费。 + cancelSuspendDelay(); +} +``` diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md index 625b3046cc8f3c16e03de8ecc96dab436b722c38..789001234202aa2ddc3a6c303a51883cfcea5eca 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,7 +2,7 @@ ## 场景介绍 -应用要执行对实时性要求不高的任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间。延迟任务调度约束见[延迟任务调度概述](./work-scheduler-overview.md)。 +应用要执行对实时性要求不高的任务或持久性任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时间。延迟任务调度约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束)。 ## 接口说明 @@ -34,7 +34,7 @@ isLastWorkTimeOut(workId: number): Promise\;| 获取上次任务是否 **表2** WorkInfo包含参数 -> **说明:** WorkInfo设置参数约束见[延迟任务调度概述](./work-scheduler-overview.md) +> **说明:** WorkInfo设置参数约束见[延迟任务调度约束](./background-task-overview.md#延迟任务调度约束) 参数名| 类型 |描述 ---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- @@ -61,138 +61,111 @@ onWorkStop(work: WorkInfo): void | 延迟调度任务结束回调 ### 开发步骤 -**开发对应的Extension** - - import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; - - export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); - } - onWorkStop(workInfo) { - console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); - } - } +1、开发对应的ExtensionAbility,用于回调执行具体的延迟任务。关于ExtensionAbility的介绍,参考[ExtensionAbility机制](../ability/stage-brief.md#extensionability机制)。 +```ts +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; -**注册延迟任务** - - import workScheduler from '@ohos.workScheduler'; - - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } +export default class MyExtension extends WorkSchedulerExtensionAbility { + onWorkStart(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); } - var res = workScheduler.startWork(workInfo); - console.info("workschedulerLog res:" + res); - - -**取消延迟任务** - - - import workScheduler from '@ohos.workScheduler'; - - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } + onWorkStop(workInfo) { + console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); } - var res = workScheduler.stopWork(workInfo, false); - console.info("workschedulerLog res:" + res); - - -**获取指定延迟任务** +} +``` -1.Callback写法 - workScheduler.getWorkStatus(50, (err, res) => { - if (err) { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); - } else { - for (let item in res) { - console.info('workschedulerLog getWorkStatuscallback success,' + item + ' is:' + res[item]); - } - } - }); +2、注册延迟任务 +```ts +import workScheduler from '@ohos.workScheduler'; -2.Promise写法 +let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } +} +var res = workScheduler.startWork(workInfo); +console.info("workschedulerLog res:" + res); +``` - workScheduler.getWorkStatus(50).then((res) => { - for (let item in res) { - console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]); - } - }).catch((err) => { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); - }) +3、取消延迟任务 -**获取所有延迟任务** +```ts +import workScheduler from '@ohos.workScheduler'; -1.Callback写法 +let workInfo = { + workId: 1, + batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, + isRepeat: false, + isPersisted: true, + bundleName: "com.example.myapplication", + abilityName: "MyExtension", + parameters: { + mykey0: 1, + mykey1: "string value", + mykey2: true, + mykey3: 1.5 + } +} +var res = workScheduler.stopWork(workInfo, false); +console.info("workschedulerLog res:" + res); +``` - workScheduler.obtainAllWorks((err, res) =>{ - if (err) { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); - } else { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); - } - }); -2.Promise写法 +4、获取指定延迟任务 - workScheduler.obtainAllWorks().then((res) => { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); - }).catch((err) => { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); - }) +```ts +workScheduler.getWorkStatus(50).then((res) => { + for (let item in res) { + console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]); + } +}).catch((err) => { + console.info('workschedulerLog getWorkStatus failed, because:' + err.code); +}) +``` -**停止并清除任务** - let res = workScheduler.stopAndClearWorks(); - console.info("workschedulerLog res:" + res); +5、获取所有延迟任务 -**判断上次执行是否超时** +```ts +workScheduler.obtainAllWorks().then((res) => { + console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); +}).catch((err) => { + console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); +}) +``` -1.Callback写法 +6、停止并清除任务 - workScheduler.isLastWorkTimeOut(500, (err, res) =>{ - if (err) { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); - } else { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); - } - }); +```ts +let res = workScheduler.stopAndClearWorks(); +console.info("workschedulerLog res:" + res); +``` -2.Promise写法 +7、判断上次执行是否超时 - workScheduler.isLastWorkTimeOut(500) - .then(res => { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); - }) - .catch(err => { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); - }); - }) +```ts +workScheduler.isLastWorkTimeOut(500) + .then(res => { + console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); + }) + .catch(err => { + console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); + }); +``` ## 相关实例 diff --git a/zh-cn/application-dev/task-management/work-scheduler-overview.md b/zh-cn/application-dev/task-management/work-scheduler-overview.md deleted file mode 100644 index da6a08d7881862a29ac15069cabfe5c47cbe77d9..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/task-management/work-scheduler-overview.md +++ /dev/null @@ -1,34 +0,0 @@ -# 延迟任务调度概述 - -延迟任务调度给应用提供一个机制,允许应用根据系统安排,在系统空闲时执行实时性不高的任务。当满足设定条件的时候,任务会被放入待调度队列,当系统空闲时调度该任务。 - -## 使用说明 - -应用要执行对实时性要求不高的任务的时候,比如设备空闲时候做一次数据学习等场景,可以使用延迟调度任务,该机制在满足应用设定条件的时候,会根据系统当前状态,如内存、功耗、温度等统一决策调度时机。 - -## 延迟任务调度约束 - -延迟调度任务的使用需要遵从如下约束和规则: - -- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[能效资源申请接口](background-task-overview.md#能效资源申请)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。 -- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。 - -应用分组 | 延迟任务执行频率约束 ---------------------|------------------------- -活跃 | 最小间隔2小时 -每日使用 | 最小间隔4小时 -经常使用 | 最小间隔24小时 -不经常使用 | 最小间隔48小时 -受限分组 | 禁止 -未使用分组 | 禁止 -[能效资源豁免分组](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | 执行频率不受限制 - -- **WorkInfo设置参数约束** - -(1) workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 - -(2)至少要设置一个满足的条件。 - -(3)重复任务时间间隔至少20分钟,当设置重复任务时间间隔时,必须设置始终重复和重复次数中的一个。 - -(4)携带参数信息支持number、string、bool三种类型。 \ No newline at end of file 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/application-dev/webgl/webgl-overview.md b/zh-cn/application-dev/webgl/webgl-overview.md index 0ec7b58b040c6ce9d5cf108fa39038f8f7fc18fc..5333e869497c351587cd4aac55025e5a5db9a208 100644 --- a/zh-cn/application-dev/webgl/webgl-overview.md +++ b/zh-cn/application-dev/webgl/webgl-overview.md @@ -1,6 +1,6 @@ # 概述 -WebGL的全称为Web Graphic Library(网页图形库),主要用于交互式渲染2D图形和3D图形。目前OpenHarmony中使用的WebGL是基于OpenGL裁剪的OpenGL ES,可以在HTML5的canvas元素对象中使用,无需使用插件,支持跨平台。WebGL程序是由JavaScript代码组成的,其中使用的API可以利用用户设备提供的GPU硬件完成图形渲染和加速。 +WebGL的全称为Web Graphic Library(网页图形库),主要用于交互式渲染2D图形和3D图形。目前OpenHarmony中使用的WebGL是基于OpenGL裁剪的OpenGL ES,可以在HTML5的canvas元素对象中使用,无需使用插件,支持跨平台。WebGL程序是由JavaScript代码组成的,其中使用的API可以利用用户设备提供的GPU硬件完成图形渲染和加速。更多信息请参考[WebGL™标准](https://www.khronos.org/registry/webgl/specs/latest/1.0/)。 ## 基本概念 diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index e230026040d48d56d29db3e75377f0c479aa9fb3..96e02fdd8648a52265c6357090a4159af16f4ff9 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -1,18 +1,28 @@ # OpenHarmony应用开发文档 + - [应用开发导读](application-dev-guide.md) - 快速开始 - - 快速入门 - [开发准备](quick-start/start-overview.md) - - [使用eTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) - - [使用eTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) + - [使用ArkTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) + - [使用ArkTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) - [使用JS语言开发(FA模型)](quick-start/start-with-js-fa.md) - - 开发基础知识 - [应用包结构说明(FA模型)](quick-start/package-structure.md) - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) + - 学习ArkTS语言 + - [初识ArkTS语言](quick-start/arkts-get-started.md) + - ArkTS语法(声明式UI) + - [基本UI描述](quick-start/arkts-basic-ui-description.md) + - 状态管理 + - [基本概念](quick-start/arkts-state-mgmt-concepts.md) + - [页面级变量的状态管理](quick-start/arkts-state-mgmt-page-level.md) + - [应用级变量的状态管理](quick-start/arkts-state-mgmt-application-level.md) + - [动态构建UI元素](quick-start/arkts-dynamic-ui-elememt-building.md) + - [渲染控制](quick-start/arkts-rendering-control.md) + - [使用限制与扩展](quick-start/arkts-restrictions-and-extensions.md) - 开发 - Ability开发 - [Ability框架概述](ability/ability-brief.md) @@ -37,7 +47,7 @@ - [测试框架使用指导](ability/ability-delegator.md) - UI开发 - [方舟开发框架(ArkUI)概述](ui/arkui-overview.md) - - 基于eTS的声明式开发范式 + - 基于ArkTS的声明式开发范式 - [概述](ui/ui-ts-overview.md) - 框架说明 - 文件组织 @@ -47,49 +57,10 @@ - [资源文件的分类](ui/ui-ts-basic-resource-file-categories.md) - [资源访问](ui/ts-resource-access.md) - [像素单位](ui/ts-pixel-units.md) - - 声明式语法 - - [描述规范使用说明](ui/ts-syntax-intro.md) - - 通用UI描述规范 - - [基本概念](ui/ts-general-ui-concepts.md) - - 声明式UI描述规范 - - [无构造参数配置](ui/ts-parameterless-configuration.md) - - [必选参数构造配置](ui/ts-configuration-with-mandatory-parameters.md) - - [属性配置](ui/ts-attribution-configuration.md) - - [事件配置](ui/ts-event-configuration.md) - - [子组件配置](ui/ts-child-component-configuration.md) - - 组件化 - - [@Component](ui/ts-component-based-component.md) - - [@Entry](ui/ts-component-based-entry.md) - - [@Preview](ui/ts-component-based-preview.md) - - [@Builder](ui/ts-component-based-builder.md) - - [@Extend](ui/ts-component-based-extend.md) - - [@CustomDialog](ui/ts-component-based-customdialog.md) - - [@Styles](ui/ts-component-based-styles.md) - - UI状态管理 - - [基本概念](ui/ts-ui-state-mgmt-concepts.md) - - 管理组件拥有的状态 - - [@State](ui/ts-component-states-state.md) - - [@Prop](ui/ts-component-states-prop.md) - - [@Link](ui/ts-component-states-link.md) - - 管理应用程序的状态 - - [应用程序的数据存储](ui/ts-application-states-appstorage.md) - - [Ability数据存储](ui/ui-ts-local-storage.md) - - [持久化数据管理](ui/ts-application-states-apis-persistentstorage.md) - - [环境变量](ui/ts-application-states-apis-environment.md) - - 其他类目的状态管理 - - [Observed和ObjectLink数据管理](ui/ts-other-states-observed-objectlink.md) - - [@Consume和@Provide数据管理](ui/ts-other-states-consume-provide.md) - - [@Watch](ui/ts-other-states-watch.md) - - 渲染控制语法 - - [条件渲染](ui/ts-rending-control-syntax-if-else.md) - - [循环渲染](ui/ts-rending-control-syntax-foreach.md) - - [数据懒加载](ui/ts-rending-control-syntax-lazyforeach.md) - 深入理解组件化 - - [build函数](ui/ts-function-build.md) - [自定义组件初始化](ui/ts-custom-component-initialization.md) - [自定义组件生命周期回调函数](ui/ts-custom-component-lifecycle-callbacks.md) - [组件创建和重新初始化示例](ui/ts-component-creation-re-initialization.md) - - [语法糖](ui/ts-syntactic-sugar.md) - 常见组件开发指导 - [Button开发指导](ui/ui-ts-basic-components-button.md) - [Web开发指导](ui/ui-ts-components-web.md) @@ -183,9 +154,6 @@ - [公共事件与通知概述](notification/notification-brief.md) - [公共事件开发指导](notification/common-event.md) - [通知开发指导](notification/notification-guidelines.md) - - 后台代理提醒 - - [后台代理提醒开发概述](notification/background-agent-scheduled-reminder-overview.md) - - [后台代理提醒开发指导](notification/background-agent-scheduled-reminder-guide.md) - [调试助手使用指导](notification/assistant-guidelines.md) - 窗口管理 - [窗口开发概述](windowmanager/window-overview.md) @@ -226,6 +194,9 @@ - 密钥管理 - [HUKS开发概述](security/huks-overview.md) - [HUKS开发指导](security/huks-guidelines.md) + - 加密算法库框架 + - [加密算法库框架概述](security/cryptoFramework-overview.md) + - [加密算法框架开发指导](security/cryptoFramework-guidelines.md) - Hap包签名工具 - [Hap包签名工具概述](security/hapsigntool-overview.md) - [Hap包签名工具指导](security/hapsigntool-guidelines.md) @@ -262,10 +233,13 @@ - 任务管理 - 后台任务 - [后台任务概述](task-management/background-task-overview.md) - - [后台任务开发指导](task-management/background-task-dev-guide.md) - - 延迟任务调度 - - [延迟任务调度概述](task-management/work-scheduler-overview.md) - - [延迟任务调度开发指导](task-management/work-scheduler-dev-guide.md) + - [短时任务开发指导](task-management/transient-task-dev-guide.md) + - [长时任务开发指导](task-management/continuous-task-dev-guide.md) + - [延迟任务开发指导](task-management/work-scheduler-dev-guide.md) + - [申请能效资源开发指导](task-management/efficiency-resources-apply-dev-guide.md) + - 后台代理提醒 + - [后台代理提醒开发概述](task-management/background-agent-scheduled-reminder-overview.md) + - [后台代理提醒开发指导](task-management/background-agent-scheduled-reminder-guide.md) - 设备管理 - USB服务 - [USB服务开发概述](device/usb-overview.md) @@ -333,18 +307,18 @@ - [资源](key-features/multi-device-app-dev/design-resources.md) - [工程管理](key-features/multi-device-app-dev/ide-using.md) - 页面开发的一多能力介绍 - - [简介](key-features/multi-device-app-dev/page-development-intro.md) - - 布局能力 - - [布局简介](key-features/multi-device-app-dev/layout-intro.md) - - [自适应布局](key-features/multi-device-app-dev/adaptive-layout.md) - - [响应式布局](key-features/multi-device-app-dev/responsive-layout.md) - - [典型布局场景](key-features/multi-device-app-dev/typical-layout-scenario.md) - - 典型页面场景 - - [应用市场首页](key-features/multi-device-app-dev/appgallery-home-page.md) - - [音乐专辑页](key-features/multi-device-app-dev/music-album-page.md) - - [交互归一](key-features/multi-device-app-dev/interaction-event-normalization.md) - - [多态组件](key-features/multi-device-app-dev/polymorphic-controls.md) - - [资源使用](key-features/multi-device-app-dev/resource-usage.md) + - [简介](key-features/multi-device-app-dev/page-development-intro.md) + - 布局能力 + - [布局简介](key-features/multi-device-app-dev/layout-intro.md) + - [自适应布局](key-features/multi-device-app-dev/adaptive-layout.md) + - [响应式布局](key-features/multi-device-app-dev/responsive-layout.md) + - [典型布局场景](key-features/multi-device-app-dev/typical-layout-scenario.md) + - 典型页面场景 + - [应用市场首页](key-features/multi-device-app-dev/appgallery-home-page.md) + - [音乐专辑页](key-features/multi-device-app-dev/music-album-page.md) + - [交互归一](key-features/multi-device-app-dev/interaction-event-normalization.md) + - [多态组件](key-features/multi-device-app-dev/polymorphic-controls.md) + - [资源使用](key-features/multi-device-app-dev/resource-usage.md) - [功能开发的一多能力介绍](key-features/multi-device-app-dev/development-intro.md) - [案例应用](key-features/multi-device-app-dev/case.md) - [常见问题](key-features/multi-device-app-dev/faq.md) @@ -354,7 +328,7 @@ - [Drawing开发指导](napi/drawing-guidelines.md) - [Rawfile开发指导](napi/rawfile-guidelines.md) - [Window开发指导](napi/native-window-guidelines.md) - - [使用MindSpore Lite引擎进行模型推理](napi/mindspore-lite-guidelines.md) + - [使用MindSpore Lite引擎进行模型推理](napi/mindspore-lite-guidelines.md) - 工具 - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - 示例教程 @@ -362,7 +336,7 @@ - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md) - API参考 - [Syscap列表](reference/syscap-list.md) - - 组件参考(基于eTS的声明式开发范式) + - 组件参考(基于ArkTS的声明式开发范式) - 组件通用信息 - 通用事件 - [点击事件](reference/arkui-ts/ts-universal-events-click.md) @@ -495,12 +469,12 @@ - 画布组件 - [Canvas](reference/arkui-ts/ts-components-canvas-canvas.md) - [CanvasRenderingContext2D对象](reference/arkui-ts/ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingConxt2D对象](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - - [Path2D对象](reference/arkui-ts/ts-components-canvas-path2d.md) - [CanvasGradient对象](reference/arkui-ts/ts-components-canvas-canvasgradient.md) - [ImageBitmap对象](reference/arkui-ts/ts-components-canvas-imagebitmap.md) - [ImageData对象](reference/arkui-ts/ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D对象](reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md) + - [Path2D对象](reference/arkui-ts/ts-components-canvas-path2d.md) + - [Lottie](reference/arkui-ts/ts-components-canvas-lottie.md) - 动画 - [属性动画](reference/arkui-ts/ts-animatorproperty.md) - [显式动画](reference/arkui-ts/ts-explicit-animation.md) @@ -509,8 +483,7 @@ - [组件内转场](reference/arkui-ts/ts-transition-animation-component.md) - [共享元素转场](reference/arkui-ts/ts-transition-animation-shared-elements.md) - [路径动画](reference/arkui-ts/ts-motion-path-animation.md) - - [矩阵变换](reference/arkui-ts/ts-matrix-transformation.md) - - [插值计算](reference/arkui-ts/ts-interpolation-calculation.md) + - 全局UI方法 - 弹窗 - [警告弹窗](reference/arkui-ts/ts-methods-alert-dialog-box.md) @@ -711,6 +684,7 @@ - [@ohos.application.formInfo (FormInfo)](reference/apis/js-apis-formInfo.md) - [@ohos.application.formProvider (FormProvider)](reference/apis/js-apis-formprovider.md) - [@ohos.application.missionManager (missionManager)](reference/apis/js-apis-missionManager.md) + - [@ohos.application.quickFixManager (quickFixManager)](reference/apis/js-apis-application-quickFixManager.md) - [@ohos.application.Want (Want)](reference/apis/js-apis-application-Want.md) - [@ohos.continuation.continuationManager (ContinuationExtraParams)](reference/apis/js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager (continuationManager)](reference/apis/js-apis-continuation-continuationManager.md) @@ -724,7 +698,7 @@ - [ProcessRunningInfo (ProcessRunningInfo)](reference/apis/js-apis-processrunninginfo.md) - [ProcessRunningInformation (ProcessRunningInformation)](reference/apis/js-apis-processrunninginformation.md) - [shellCmdResult (ShellCmdResult)](reference/apis/js-apis-application-shellCmdResult.md) - - [ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md) + - continuation/[ContinuationResult (ContinuationResult)](reference/apis/js-apis-continuation-continuationResult.md) - 公共事件与通知 - [@ohos.commonEvent (公共事件模块)](reference/apis/js-apis-commonEvent.md) - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) @@ -751,10 +725,10 @@ - [LauncherAbilityInfo (LauncherAbilityInfo)](reference/apis/js-apis-bundle-LauncherAbilityInfo.md) - [Metadata (Metadata)](reference/apis/js-apis-bundle-Metadata.md) - [ModuleInfo (ModuleInfo)](reference/apis/js-apis-bundle-ModuleInfo.md) + - [PackInfo (PackInfo)](reference/apis/js-apis-bundle-PackInfo.md) - [PermissionDef (PermissionDef)](reference/apis/js-apis-bundle-PermissionDef.md) - [RemoteAbilityInfo (RemoteAbilityInfo)](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [ShortcutInfo (ShortcutInfo)](reference/apis/js-apis-bundle-ShortcutInfo.md) - - [PackInfo (PackInfo)](reference/apis/js-apis-bundle-PackInfo.md) - UI界面 - [@ohos.animator (动画)](reference/apis/js-apis-animator.md) - [@ohos.mediaquery (媒体查询)](reference/apis/js-apis-mediaquery.md) @@ -793,8 +767,8 @@ - 安全 - [@ohos.abilityAccessCtrl (访问控制管理)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (隐私管理)](reference/apis/js-apis-privacyManager.md) + - [@ohos.security.cryptoFramework (加密算法库框架)](reference/apis/js-apis-cryptoFramework.md) - [@ohos.security.huks (通用密钥库系统)](reference/apis/js-apis-huks.md) - - [@ohos.security.cryptoFramework (加解密算法库框架)](reference/apis/js-apis-cryptoFramework.md) - [@ohos.userIAM.faceAuth (人脸认证)](reference/apis/js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth (用户认证)](reference/apis/js-apis-useriam-userauth.md) - [@system.cipher (加密算法)](reference/apis/js-apis-system-cipher.md) @@ -810,10 +784,11 @@ - [@ohos.data.ValuesBucket (数据集)](reference/apis/js-apis-data-ValuesBucket.md) - [resultSet (结果集)](reference/apis/js-apis-data-resultset.md) - 文件管理 + - [@ohos.data.fileAccess (公共文件访问与管理)](reference/apis/js-apis-fileAccess.md) - [@ohos.document (文件交互)](reference/apis/js-apis-document.md) - [@ohos.environment (目录环境能力)](reference/apis/js-apis-environment.md) + - [@ohos.fileExtensionInfo (公共文件访问与管理属性信息)](reference/apis/js-apis-fileExtensionInfo.md) - [@ohos.fileio (文件管理)](reference/apis/js-apis-fileio.md) - - [@ohos.fileManager (公共文件访问与管理)](reference/apis/js-apis-filemanager.md) - [@ohos.filemanagement.userfile_manager (用户数据管理)](reference/apis/js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary (媒体库管理)](reference/apis/js-apis-medialibrary.md) - [@ohos.securityLabel (数据标签)](reference/apis/js-apis-securityLabel.md) @@ -861,13 +836,13 @@ - [@ohos.hiSysEvent (系统事件打点)](reference/apis/js-apis-hisysevent.md) - [@ohos.hiTraceChain (分布式跟踪)](reference/apis/js-apis-hitracechain.md) - [@ohos.hiTraceMeter (性能打点)](reference/apis/js-apis-hitracemeter.md) - - [@ohos.inputMethod (输入法框架)](reference/apis/js-apis-inputmethod.md) - - [@ohos.inputMethodEngine (输入法服务)](reference/apis/js-apis-inputmethodengine.md) + - [@ohos.inputmethod (输入法框架)](reference/apis/js-apis-inputmethod.md) + - [@ohos.inputmethodengine (输入法服务)](reference/apis/js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability (InputMethodExtensionAbility)](reference/apis/js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext (InputMethodExtensionContext)](reference/apis/js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard (剪贴板)](reference/apis/js-apis-pasteboard.md) - [@ohos.screenLock (锁屏管理)](reference/apis/js-apis-screen-lock.md) - - [@ohos.systemTime (系统时区、时间)](reference/apis/js-apis-system-time.md) + - [@ohos.systemTime (系统时间、时区)](reference/apis/js-apis-system-time.md) - [@ohos.systemTimer(系统定时器)](reference/apis/js-apis-system-timer.md) - [@ohos.wallpaper (壁纸)](reference/apis/js-apis-wallpaper.md) - [Timer (定时器)](reference/apis/js-apis-timer.md) @@ -949,6 +924,7 @@ - [@system.storage (数据存储)](reference/apis/js-apis-system-storage.md) - [@system.vibrator (振动)](reference/apis/js-apis-system-vibrate.md) - [console (日志打印)](reference/apis/js-apis-logs.md) + - 接口参考(Native API) - 模块 - [Native XComponent](reference/native-apis/_o_h___native_x_component.md) @@ -1018,7 +994,7 @@ - [full-SDK替换指南](quick-start/full-sdk-switch-guide.md) - [Ability框架开发常见问题](faqs/faqs-ability.md) - [UI框架(JS)开发常见问题](faqs/faqs-ui-js.md) - - [UI框架(eTS)开发常见问题](faqs/faqs-ui-ets.md) + - [UI框架(ArkTS)开发常见问题](faqs/faqs-ui-ets.md) - [图形图像开发常见问题](faqs/faqs-graphics.md) - [文件管理开发常见问题](faqs/faqs-file-management.md) - [网络与连接开发常见问题](faqs/faqs-connectivity.md) diff --git a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md index bdb313049f79ebdcb397c7668b35cff66ecaa9cb..c7dc8513b9e69d1dc158868e95350200c7952c6c 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md @@ -36,51 +36,51 @@ USB驱动模型Host侧开放的API接口功能,参考USB Host驱动模型图 | int32_t UsbInitHostSdk(struct UsbSession \*\*session); | USB主机端驱动开发工具包初始化 | | int32_t UsbExitHostSdk(const struct UsbSession
\*session); | USB主机端驱动开发工具包退出 | | const struct UsbInterface \*UsbClaimInterface(const
struct UsbSession \*session, uint8_t busNum, uint8_t
usbAddr, uint8_t interfaceIndex); | 获取USB接口对象 | -| int UsbReleaseInterface(const struct UsbInterface
\*interfaceObj); | 释放USB接口对象 | -| int UsbAddOrRemoveInterface(const struct UsbSession
\*session, uint8_t busNum, uint8_t usbAddr, uint8_t
interfaceIndex, UsbInterfaceStatus status); | 增加移除接口 | +| int32_t UsbReleaseInterface(const struct UsbInterface
\*interfaceObj); | 释放USB接口对象 | +| int32_t UsbAddOrRemoveInterface(const struct UsbSession
\*session, uint8_t busNum, uint8_t usbAddr, uint8_t
interfaceIndex, UsbInterfaceStatus status); | 增加移除接口 | | UsbInterfaceHandle \*UsbOpenInterface(const struct
UsbInterface \*interfaceObj); | 打开USB对象接口 | | int32_t UsbCloseInterface(const UsbInterfaceHandle
\*interfaceHandle); | 关闭USB接口对象 | | int32_t UsbSelectInterfaceSetting(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
settingIndex, struct UsbInterface \*\*interfaceObj); | 设置可选配置 | | int32_t UsbGetPipeInfo(const UsbInterfaceHandle
\*interfaceHandle, uint8_t settingIndex, uint8_t pipeId,
struct UsbPipeInfo \*pipeInfo); | 获取指定可选设置的管道信息 | | int32_t UsbClearInterfaceHalt(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
pipeAddress); | 清除指定索引的管道状态 | -| struct UsbRequest \*UsbAllocRequest(const
UsbInterfaceHandle \*interfaceHandle, int isoPackets
, int length); | 分配请求对象 | -| int UsbFreeRequest(const struct UsbRequest
\*request); | 释放请求对象 | -| int UsbSubmitRequestAsync(const struct UsbRequest
\*request); | 发送异步请求 | +| struct UsbRequest \*UsbAllocRequest(const
UsbInterfaceHandle \*interfaceHandle, int32_t isoPackets
, int32_t length); | 分配请求对象 | +| int32_t UsbFreeRequest(const struct UsbRequest
\*request); | 释放请求对象 | +| int32_t UsbSubmitRequestAsync(const struct UsbRequest
\*request); | 发送异步请求 | | int32_t UsbFillRequest(const struct UsbRequest
\*request, const UsbInterfaceHandle \*interfaceHandle,
const struct UsbRequestParams \*params); | 填充请求 | -| sint UsbCancelRequest(const struct UsbRequest
\*request); | 取消异步请求 | -| int UsbSubmitRequestSync(const struct UsbRequest
\*request); | 发送同步请求 | +| int32_t UsbCancelRequest(const struct UsbRequest
\*request); | 取消异步请求 | +| int32_t UsbSubmitRequestSync(const struct UsbRequest
\*request); | 发送同步请求 | **表2** usb_raw_api.h | 接口名称 | 功能描述 | | -------- | -------- | -| int UsbRawInit(struct UsbSession \*\*session); | USB驱动开发工具包专家模式初始化 | -| int UsbRawExit(const struct UsbSession \*session); | USB驱动开发工具包专家模式退出 | +| int32_t UsbRawInit(struct UsbSession \*\*session); | USB驱动开发工具包专家模式初始化 | +| int32_t UsbRawExit(const struct UsbSession \*session); | USB驱动开发工具包专家模式退出 | | UsbRawHandle \*UsbRawOpenDevice(const struct
UsbSession \*session, uint8_t busNum, uint8_t
usbAddr); | 打开USB设备对象 | -| int UsbRawCloseDevice(const UsbRawHandle
\*devHandle); | 关闭USB设备对象 | -| int UsbRawSendControlRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbControlRequestData
\*requestData); | 执行同步控制传输 | -| int UsbRawSendBulkRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步批量传输 | -| int UsbRawSendInterruptRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步中断传输 | -| int UsbRawGetConfigDescriptor(const UsbRawDevice
\*rawDev, uint8_t configIndex, struct
UsbRawConfigDescriptor \*\*config); | 获取给定设备指定ID的设备配置描述符 | +| int32_t UsbRawCloseDevice(const UsbRawHandle
\*devHandle); | 关闭USB设备对象 | +| int32_t UsbRawSendControlRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbControlRequestData
\*requestData); | 执行同步控制传输 | +| int32_t UsbRawSendBulkRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步批量传输 | +| int32_t UsbRawSendInterruptRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步中断传输 | +| int32_t UsbRawGetConfigDescriptor(const UsbRawDevice
\*rawDev, uint8_t configIndex, struct
UsbRawConfigDescriptor \*\*config); | 获取给定设备指定ID的设备配置描述符 | | void UsbRawFreeConfigDescriptor(const struct
UsbRawConfigDescriptor \*config); | 释放配置描述符内存空间 | -| int UsbRawGetConfiguration(const UsbRawHandle
\*devHandle, int \*config); | 获取当前激活配置 | -| int UsbRawSetConfiguration(const UsbRawHandle
\*devHandle, int config); | 设置当前激活配置 | -| int UsbRawGetDescriptor(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawDescriptorParam \*param, const unsigned char
\*data); | 获取描述符信息 | +| int32_t UsbRawGetConfiguration(const UsbRawHandle
\*devHandle, int32_t \*config); | 获取当前激活配置 | +| int32_t UsbRawSetConfiguration(const UsbRawHandle
\*devHandle, int32_t config); | 设置当前激活配置 | +| int32_t UsbRawGetDescriptor(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawDescriptorParam \*param, const unsigned char
\*data); | 获取描述符信息 | | UsbRawDevice \*UsbRawGetDevice(const UsbRawHandle
\*devHandle); | 由设备句柄获取设备指针 | -| int UsbRawGetDeviceDescriptor(const UsbRawDevice
\*rawDev, struct
UsbDeviceDescriptor \*desc); | 获取给定设备的USB设备描述符 | -| int UsbRawClaimInterface(const UsbRawHandle
\*devHandle, int
interfaceNumber); | 声明给定设备句柄上的接口 | -| int UsbRawReleaseInterface(const UsbRawHandle
\*devHandle, in
t interfaceNumber); | 释放之前声明的接口 | -| int UsbRawResetDevice(const UsbRawHandle
\*devHandle); | 复位设备 | -| struct UsbRawRequest \*UsbRawAllocRequest(const
UsbRawHandle
\*devHandle, int isoPackets, int length); | 分配一个带有指定数量的同步包描述符的传输请求 | -| int UsbRawFreeRequest(const struct UsbRawRequest
\*request); | 释放之前分配的传输请求 | -| int UsbRawFillBulkRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充批量传输请求所需信息 | -| int UsbRawFillControlSetup(const unsigned char \*setup,
const struct UsbControlRequestData \*requestData); | 填充控制传输设置包所需信息 | -| int UsbRawFillControlRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充控制传输请求所需信息 | -| int UsbRawFillInterruptRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充中断传输请求所需信息 | -| int UsbRawFillIsoRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充同步传输(Isochronous Transfers)请求所需信息 | -| int UsbRawSubmitRequest(const struct UsbRawRequest
\*request); | 提交一个传输请求 | -| int UsbRawCancelRequest(const struct UsbRawRequest
\*request); | 取消一个传输请求 | -| int UsbRawHandleRequests(const UsbRawHandle
\*devHandle); | 传输请求事件完成处理 | +| int32_t UsbRawGetDeviceDescriptor(const UsbRawDevice
\*rawDev, struct
UsbDeviceDescriptor \*desc); | 获取给定设备的USB设备描述符 | +| int32_t UsbRawClaimInterface(const UsbRawHandle
\*devHandle, int32_t
interfaceNumber); | 声明给定设备句柄上的接口 | +| int32_t UsbRawReleaseInterface(const UsbRawHandle
\*devHandle, in
t interfaceNumber); | 释放之前声明的接口 | +| int32_t UsbRawResetDevice(const UsbRawHandle
\*devHandle); | 复位设备 | +| struct UsbRawRequest \*UsbRawAllocRequest(const
UsbRawHandle
\*devHandle, int32_t isoPackets, int32_t length); | 分配一个带有指定数量的同步包描述符的传输请求 | +| int32_t UsbRawFreeRequest(const struct UsbRawRequest
\*request); | 释放之前分配的传输请求 | +| int32_t UsbRawFillBulkRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充批量传输请求所需信息 | +| int32_t UsbRawFillControlSetup(const unsigned char \*setup,
const struct UsbControlRequestData \*requestData); | 填充控制传输设置包所需信息 | +| int32_t UsbRawFillControlRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充控制传输请求所需信息 | +| int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充中断传输请求所需信息 | +| int32_t UsbRawFillIsoRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充同步传输(Isochronous Transfers)请求所需信息 | +| int32_t UsbRawSubmitRequest(const struct UsbRawRequest
\*request); | 提交一个传输请求 | +| int32_t UsbRawCancelRequest(const struct UsbRawRequest
\*request); | 取消一个传输请求 | +| int32_t UsbRawHandleRequests(const UsbRawHandle
\*devHandle); | 传输请求事件完成处理 | USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型图。 @@ -89,19 +89,19 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | 接口名称 | 功能描述 | | -------- | -------- | | const struct UsbFnDevice \*UsbFnCreateDevice(const
char \*udcName, const struct UsbFnDescriptorData
\*descriptor); | 创建USB设备 | -| int UsbFnRemoveDevice(struct UsbFnDevice
\*fnDevice); | 删除USB设备 | +| int32_t UsbFnRemoveDevice(struct UsbFnDevice
\*fnDevice); | 删除USB设备 | | const struct UsbFnDevice \*UsbFnGetDevice(const char
\*udcName); | 获取USB设备 | **表4** usbfn_interface.h | 接口名称 | 功能描述 | | -------- | -------- | -| int UsbFnStartRecvInterfaceEvent(struct
UsbFnInterface \*interface, uint32_t eventMask,
UsbFnEventCallback callback, void \*context); | 开始接受Event事件 | -| int UsbFnStopRecvInterfaceEvent(struct
UsbFnInterface \*interface); | 停止接受Event事件 | +| int32_t UsbFnStartRecvInterfaceEvent(struct
UsbFnInterface \*interface, uint32_t eventMask,
UsbFnEventCallback callback, void \*context); | 开始接受Event事件 | +| int32_t UsbFnStopRecvInterfaceEvent(struct
UsbFnInterface \*interface); | 停止接受Event事件 | | UsbFnInterfaceHandle UsbFnOpenInterface(struct UsbFnInterface \*interface); | 打开一个接口 | -| int UsbFnCloseInterface(UsbFnInterfaceHandle handle); | 关闭一个接口 | -| int UsbFnGetInterfacePipeInfo(struct UsbFnInterface
\*interface, uint8_t pipeId, struct UsbFnPipeInfo \*info); | 获取管道信息 | -| int UsbFnSetInterfaceProp(const struct UsbFnInterface
\*interface, const char \*name, const char \*value); | 设置自定义属性 | +| int32_t UsbFnCloseInterface(UsbFnInterfaceHandle handle); | 关闭一个接口 | +| int32_t UsbFnGetInterfacePipeInfo(struct UsbFnInterface
\*interface, uint8_t pipeId, struct UsbFnPipeInfo \*info); | 获取管道信息 | +| int32_t UsbFnSetInterfaceProp(const struct UsbFnInterface
\*interface, const char \*name, const char \*value); | 设置自定义属性 | **表5** usbfn_request.h @@ -109,10 +109,10 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | -------- | -------- | | struct UsbFnRequest
\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle,
uint32_t len); | 申请一个控制请求 | | struct UsbFnRequest \*UsbFnAllocRequest(UsbFnInterfaceHandle handle,
uint8_t pipe, uint32_t len); | 申请一个数据请求 | -| int UsbFnFreeRequest(struct UsbFnRequest \*req); | 释放一个请求 | -| int UsbFnSubmitRequestAsync(struct UsbFnRequest
\*req); | 发送异步请求 | -| int UsbFnSubmitRequestSync(struct UsbFnRequest
\*req, uint32_t timeout); | 发送同步请求 | -| int UsbFnCancelRequest(struct UsbFnRequest \*req); | 取消请求 | +| int32_t UsbFnFreeRequest(struct UsbFnRequest \*req); | 释放一个请求 | +| int32_t UsbFnSubmitRequestAsync(struct UsbFnRequest
\*req); | 发送异步请求 | +| int32_t UsbFnSubmitRequestSync(struct UsbFnRequest
\*req, uint32_t timeout); | 发送同步请求 | +| int32_t UsbFnCancelRequest(struct UsbFnRequest \*req); | 取消请求 | ## 开发步骤 @@ -218,6 +218,9 @@ root { } } } +``` + +```cpp #include "usb_serial.h" #include "hdf_base.h" @@ -236,10 +239,10 @@ static struct UsbRequest *g_ctrlCmdRequest = NULL; static bool g_acmReleaseFlag = false; static uint8_t *g_acmReadBuffer = NULL; ... -static int SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, +static int32_t SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, uint16_t value, void *buf, uint16_t len) { - int ret; + int32_t ret; uint16_t index = acm->intPipe->interfaceId; struct UsbControlParams controlParams; struct UsbRequestParams params; @@ -299,7 +302,7 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, uint8_t interfaceIndex, UsbPipeType pipeType, UsbPipeDirection pipeDirection) { uint8_t i; - int ret; + int32_t ret; struct UsbInterfaceInfo *info = NULL; UsbInterfaceHandle *interfaceHandle = NULL; if (pipeType == USB_PIPE_TYPE_CONTROL) @@ -408,11 +411,11 @@ error: return HDF_FAILURE; } ... -static int AcmAllocReadRequests(struct AcmDevice *acm) +static int32_t AcmAllocReadRequests(struct AcmDevice *acm) { - int ret; + int32_t ret; struct UsbRequestParams readParams; - for (int i = 0; i < ACM_NR; i++) { + for (int32_t i = 0; i < ACM_NR; i++) { acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // 分配待发送的readReq IO Request对象 if (!acm->readReq[i]) { HDF_LOGE("readReq request failed"); @@ -441,9 +444,9 @@ error: return HDF_ERR_MALLOC_FAIL; } -static int AcmAllocNotifyRequest(struct AcmDevice *acm) +static int32_t AcmAllocNotifyRequest(struct AcmDevice *acm) { - int ret; + int32_t ret; struct UsbRequestParams intParams = {}; acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // 分配待发送的中断IO Request对象 if (!acm->notifyReq) { @@ -474,7 +477,7 @@ error: static void AcmReleaseInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { UsbReleaseInterface(acm->iface[i]); acm->iface[i] = NULL; @@ -488,7 +491,7 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) static int32_t AcmClaimInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // 获取UsbInterface接口对象 if (acm->iface[i] == NULL) { HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]); @@ -511,7 +514,7 @@ static int32_t AcmClaimInterfaces(struct AcmDevice *acm) static void AcmCloseInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->devHandle[i]) { UsbCloseInterface(acm->devHandle[i]); acm->devHandle[i] = NULL; @@ -525,7 +528,7 @@ static void AcmCloseInterfaces(struct AcmDevice *acm) static int32_t AcmOpenInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // 打开获取到的UsbInterface接口对象 if (acm->devHandle[i] == NULL) { @@ -606,7 +609,7 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm) return HDF_ERR_MALLOC_FAIL; } - for (int i = 0; i < ACM_NW; i++) { + for (int32_t i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &(acm->wb[i]); snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); //分配待发送的IO Request对象 snd->instance = acm; @@ -789,7 +792,7 @@ HDF_INIT(g_usbSerialDriverEntry); ### Host RAW API驱动开发 -``` +```cpp root { module = "usb_pnp_device"; usb_pnp_config { @@ -836,7 +839,9 @@ root { } } } +``` +```cpp #include "usb_serial_rawapi.h" #include #include "osal_mem.h" @@ -858,11 +863,11 @@ struct OsalMutex g_stopIoLock; static bool g_rawAcmReleaseFlag = false; ...... -static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config) +static int32_t UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config) { UsbRawDevice *dev = NULL; - int activeConfig; - int ret; + int32_t activeConfig; + int32_t ret; if (devHandle == NULL) { HDF_LOGE("%s:%d devHandle is NULL", @@ -893,9 +898,9 @@ static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDe return HDF_SUCCESS; } ... -static int UsbAllocWriteRequests(struct AcmDevice *acm) +static int32_t UsbAllocWriteRequests(struct AcmDevice *acm) { - int i; + int32_t i; for (i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &acm->wb[i]; @@ -965,13 +970,13 @@ error: return HDF_FAILURE; } ... -static int UsbAllocReadRequests(struct AcmDevice *acm) +static int32_t UsbAllocReadRequests(struct AcmDevice *acm) { struct UsbRawFillRequestData reqData; - int size = acm->dataInEp->maxPacketSize; - int ret; + int32_t size = acm->dataInEp->maxPacketSize; + int32_t ret; - for (int i = 0; i < ACM_NR; i++) { + for (int32_t i = 0; i < ACM_NR; i++) { acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->readReq[i]) { HDF_LOGE("readReq request failed"); @@ -996,11 +1001,11 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) return HDF_SUCCESS; } ... -static int UsbAllocNotifyRequest(struct AcmDevice *acm) +static int32_t UsbAllocNotifyRequest(struct AcmDevice *acm) { struct UsbRawFillRequestData fillRequestData; - int size = acm->notifyEp->maxPacketSize; - int ret; + int32_t size = acm->notifyEp->maxPacketSize; + int32_t ret; acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->notifyReq) { @@ -1226,9 +1231,8 @@ HDF_INIT(g_usbSerialRawDriverEntry); USB ACM设备核心代码路径为drivers\peripheral\usb\gadget\function\acm\cdcacm.c。其使用示例如下所示,首先根据描述符创建设备,然后获取接口,打开接口,获取Pipe信息,接收Event事件,接着进行USB通信(读写等),设备卸载时候,关闭接口,停止Event接收,删除设备。 - -``` 1、创建设备 +```cpp static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct DeviceResourceIface *iface) { @@ -1251,7 +1255,9 @@ if (useHcs == 0) { } ... } +``` 2、获取接口,打开接口,获取Pipe信息 +```cpp static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface) { ... @@ -1277,8 +1283,11 @@ static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *f } return HDF_SUCCESS; } +``` + 3、接收Event事件 -static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int num) +```cpp +static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int32_t num) { ... req = UsbFnCtrlRequestAlloc(acm->ctrlIface.handle, @@ -1292,7 +1301,9 @@ static int32_t AcmDriverInit(struct HdfDeviceObject *device) ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); ... } +``` 4、进行USB通信(读写等) +```cpp static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, uint16_t value, void *data, uint32_t length) { @@ -1301,7 +1312,9 @@ static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, ret = UsbFnRequestSubmitAsync(req); ... } +``` 5、关闭接口,停止Event接收,删除设备 +```cpp static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm) { int32_t ret; diff --git a/zh-cn/device-dev/get-code/sourcecode-acquire.md b/zh-cn/device-dev/get-code/sourcecode-acquire.md index 7fb9f4c4c51323d740ad6cf5d3da5bed2d20fbec..b341943bb88fe552c418b6426e560cb484105869 100644 --- a/zh-cn/device-dev/get-code/sourcecode-acquire.md +++ b/zh-cn/device-dev/get-code/sourcecode-acquire.md @@ -12,7 +12,7 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 ## 获取源码概述 -本文档将介绍如何获取OpenHarmony源码并说明OpenHarmony的源码目录结构。OpenHarmony的代码以[组件](../hpm-part/Readme-CN.md)的形式开放,开发者可以通过如下其中一种方式获取: +本文档将介绍如何获取OpenHarmony源码并说明OpenHarmony的源码目录结构。OpenHarmony的代码以[组件](../hpm-part/hpm-part-about.md)的形式开放,开发者可以通过如下其中一种方式获取: - **获取方式1**:从码云代码仓库获取。通过repo或git工具从代码仓库中下载,此方式可获取最新代码。 @@ -77,7 +77,12 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> Master主干为开发分支,开发者可通过Master主干获取最新特性。发布版本代码相对比较稳定,开发者可基于发布版本代码进行商用功能开发。 +> +> 发布版本代码相对比较稳定,开发者可基于发布版本代码进行商用功能开发。Master主干为开发分支,开发者可通过Master主干获取最新特性。 + +- **OpenHarmony发布版本代码获取** + + OpenHarmony发布版本获取源码方式请参考[Release Notes](../../release-notes/Readme.md)。 - **OpenHarmony主干代码获取** @@ -98,10 +103,6 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 repo forall -c 'git lfs pull' ``` -- **OpenHarmony发布版本代码获取** - - OpenHarmony发布版本获取源码方式请参考[Release Notes](../../release-notes/Readme.md)。 - ## 获取方式2:从DevEco Marketplace获取 diff --git a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png index 4a959db1206c500c0ee61e1548ffa4c94565d104..f4c4e437a0089ac5ba3371f531694daac4b36703 100644 Binary files a/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png and b/zh-cn/device-dev/kernel/figures/zh-cn_image-20220930141628922.png differ 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/device-dev/security/security-guidelines-overall.md b/zh-cn/device-dev/security/security-guidelines-overall.md index 948fccd9efb8611098db00444917a9f30a8a1af5..465d5b3117c96acf458c488d491787b30bd64767 100644 --- a/zh-cn/device-dev/security/security-guidelines-overall.md +++ b/zh-cn/device-dev/security/security-guidelines-overall.md @@ -9,6 +9,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo **图1** 安全保障示意图 + ![zh-cn_image_0000001058270836](figures/zh-cn_image_0000001058270836.png) @@ -73,7 +74,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo 下图描述了DAC在文件访问时的鉴权过程,首先匹配进程uid和文件uid属性,其次匹配进程gid和文件gid属性,最后都匹配失败的情况,判断文件other属性是否支持进程的读、写、执行操作。同时支持忽略DAC检测机制(读、写、执行)作为一组系统特权(Capability),支持高权限(如系统服务)对低权限(三方APP)的文件管理。 **图2** DAC流程图 - + ![zh-cn_image_0000001057233092](figures/zh-cn_image_0000001057233092.png) - **Capability机制** @@ -102,6 +103,7 @@ OpenHarmony操作系统是一个开放的系统,开发者可以通过OpenHarmo HUKS(OpenHarmony Universal Keystore Service),提供了密钥管理、证书管理服务,当前在OpenHarmony上主要提供密钥管理服务,用于支撑HiChain(设备身份认证平台)的基础设备认证。如下是HUKS的功能结构图: **图3** HUKS功能结构图 + ![zh-cn_image_0000001159520844](figures/zh-cn_image_0000001159520844.png) 支持算法包括: @@ -144,6 +146,7 @@ HUKS本身不考虑多个应用同时调用的情况,因为HUKS只是一个lib **图4** 设备间建立可信关系流程图 + ![zh-cn_image_0000001058382954](figures/zh-cn_image_0000001058382954.png) diff --git a/zh-cn/device-dev/security/security.md b/zh-cn/device-dev/security/security.md deleted file mode 100644 index 1d9db4c8610e88ab991a455bc8be6fc56db2e36c..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/security/security.md +++ /dev/null @@ -1,7 +0,0 @@ -# 隐私与安全 - -- **[隐私保护](security-privacy-protection.md)** - -- **[安全指南](security-guidelines-overall.md)** - - diff --git a/zh-cn/device-dev/subsystems/subsys-tel.md b/zh-cn/device-dev/subsystems/subsys-tel.md deleted file mode 100644 index 18fb1c222599057d529dbf0547723e8cc8b270e6..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-tel.md +++ /dev/null @@ -1,7 +0,0 @@ -# 电话服务 - - - -- **[电话服务概述](subsys-tel-overview.md)** - -- **[电话服务开发指导](subsys-tel-guide.md)** \ No newline at end of file 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)”部分。 ## 目录 diff --git a/zh-cn/release-notes/OpenHarmony-v3.1-release.md b/zh-cn/release-notes/OpenHarmony-v3.1-release.md index 046c3317e6a37dd20492f8b4f5e81284c49ab3ba..bc1018830bfcb168b3f56b7767cebd4ecc851213 100755 --- a/zh-cn/release-notes/OpenHarmony-v3.1-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1-release.md @@ -190,7 +190,7 @@ repo forall -c 'git lfs pull' API变更请参考: -_[API差异报告](api-change/v3.1-Release/readme.md)_ +_[API差异报告](api-change/v3.1-Release/Readme-CN.md)_ ### 芯片及开发板适配 @@ -215,7 +215,7 @@ _[API差异报告](api-change/v3.1-Release/readme.md)_ | ArkUI | [拖拽](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag) | 本示例主要展示了拖拽操作的功能。 | eTS | | ArkUI | [动画](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation) | 本示例通过点击按钮触发动画,向用户展示属性动画与显示动画的效果。 | eTS | | 数据管理 | [分布式数据库-结果集和谓词查询](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery) | 本示例展示了分布式数据管理中,如何通过构建query对象, 查询kvstore中的数据,获取结果集。 | eTS | -| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) | 本示例展示了在eTS中关系型数据库的使用,包括增、删、改、查等操作。 | eTS | +| 数据管理 | [关系型数据库](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | 本示例展示了在eTS中关系型数据库的使用,包括增、删、改、查等操作。 | eTS | | 事件 | [后台代理提醒](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) | 本示例通过模拟闹钟来展示后台代理提醒的使用方法。 | eTS | | 事件 | [事件通知](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter) | 本示例主要展示进程内事件通知,用户通过选择对应商品并提交订单后在订单列表显示所选商品。 | eTS | | 通信与连接 | [RPC通信](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC) | 本示例展示了同一设备中前后台的数据交互,用户前台选择相应的商品与数目,后台计算出结果,回传给前台展示。 | eTS | @@ -248,10 +248,10 @@ _[API差异报告](api-change/v3.1-Release/readme.md)_ | ISSUE单 | 问题描述 | | -------- | -------- | | [I4MGJM](https://gitee.com/openharmony/drivers_peripheral/issues/I4MGJM) | 【hdf/camera】RK3568单板跑camera HDI用例失败 | -| [I4OECR](https://gitee.com/openharmony/ark_js_runtime/issues/I4OECR) | XTS运行报ark异常栈(低概率问题) | -| [I4OBTW](https://gitee.com/openharmony/aafwk_standard/issues/I4OBTW) | 全量执行XTS用例,安装应用后出现批量aa start 失败,影响社区流水线稳定性测试 | -| [I4OLHF](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLHF?from=project-issue) | 【ArkUI子系统】 由进程com.amsst.amsMissionSnapshotTest导致测试进程异常 | -| [I4OLUK](https://gitee.com/openharmony/ark_js_runtime/issues/I4OLUK) | 【ArkUI子系统】 由进程com.ohos.systemui导致进程栈异常 | +| I4OECR | XTS运行报ark异常栈(低概率问题) | +| I4OBTW | 全量执行XTS用例,安装应用后出现批量aa start 失败,影响社区流水线稳定性测试 | +| I4OLHF | 【ArkUI子系统】 由进程com.amsst.amsMissionSnapshotTest导致测试进程异常 | +| I4OLUK | 【ArkUI子系统】 由进程com.ohos.systemui导致进程栈异常 | ## 遗留缺陷列表 diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md index 1a05a0e689fb773071c779e82d03e3be67a48889..1819cdbe09524576f272ccba0dd36b38790b2de9 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta1.md @@ -173,7 +173,7 @@ ArkUI支持AbilityComponent组件将应用界面(Ability)作为控件嵌入 ### API变更 -_[API差异报告](api-change/v3.2-beta1/readme.md)_ +_[API差异报告](api-change/v3.2-beta1/Readme-CN.md)_ ### 芯片及开发板适配 diff --git a/zh-cn/release-notes/api-change/v3.1-Release/readme.md b/zh-cn/release-notes/api-change/v3.1-Release/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.1-Release/readme.md rename to zh-cn/release-notes/api-change/v3.1-Release/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta1/readme.md b/zh-cn/release-notes/api-change/v3.2-beta1/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta1/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta1/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/readme.md b/zh-cn/release-notes/api-change/v3.2-beta2/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta2/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta2/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md index b218e9aecd626766f51f3e1a2b5249f0b53a6762..0871a6dec65c5967fad00a06033d09856105182d 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md +++ b/zh-cn/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md @@ -55,4 +55,39 @@ OpenHarmony应用沙箱组件 ![](figures/compile-change2-1.png) -![](figures/compile-change2-2.png) \ No newline at end of file +![](figures/compile-change2-2.png) + +**变更3**:状态变量多种数据类型声明使用限制。 + +状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 + +示例: + +```ts +@Entry +@Component +struct Index { + //错误写法: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**关键的接口/组件变更** + +无 + +**适配指导** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 \ No newline at end of file diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/readme.md b/zh-cn/release-notes/api-change/v3.2-beta3/Readme-CN.md similarity index 100% rename from zh-cn/release-notes/api-change/v3.2-beta3/readme.md rename to zh-cn/release-notes/api-change/v3.2-beta3/Readme-CN.md diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md index 48b3fb3ed9d96a59e63451b2aa1010d5298c3cda..411ee5c31b0bbafb237fae401acf30963693cc49 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md @@ -172,6 +172,41 @@ FA模型下的公共模块变量共享之前是作为需求交付的,在中间 无 +### 状态变量多种数据类型声明使用限制。 + +状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。 + +示例: + +```ts +@Entry +@Component +struct Index { + //错误写法: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**变更影响** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,编译报错提示不支持。 + +**关键的接口/组件变更** + +当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。 + ## 全球化子系统 ### 针对color.json中颜色值,增加合法性校验