diff --git a/CODEOWNERS b/CODEOWNERS index cd5e192f6dfec673acfd1a1c594cb33b3a173978..9b63d1bbd03930ed56c660264086ffc1266a52f8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -144,6 +144,8 @@ zh-cn/application-dev/telephony/ @zengyawen zh-cn/application-dev/dfx/ @zengyawen zh-cn/application-dev/database/ @ge-yafang zh-cn/application-dev/napi/drawing_guidelines.md @ge-yafang +zh-cn/application-dev/napi/native-window-guidelines.md @ge-yafang +zh-cn/application-dev/napi/mindspore-lite-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile_guidelines.md @HelloCrease zh-cn/application-dev/background-agent-scheduled-reminder/ @RayShih zh-cn/application-dev/background-task-management/ @RayShih @@ -164,6 +166,22 @@ zh-cn/application-dev/reference/arkui-js/ @HelloCrease zh-cn/application-dev/reference/arkui-ts/ @HelloCrease zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-lib @RayShih +zh-cn/application-dev/quick-start/start-overview.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-fa.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-js-fa.md @ge-yafang +zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang +zh-cn/application-dev/quick-start/package-structure.md @RayShih +zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih +zh-cn/application-dev/quick-start/syscap.md @RayShih +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/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 zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @RayShih @@ -186,7 +204,6 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-uripermissionmanager.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-Want.md @RayShih zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @RayShih zh-cn/application-dev/reference/apis/js-apis-dataAbilityHelper.md @RayShih @@ -209,7 +226,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 @@ -277,15 +294,15 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-tagSession.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @RayShih zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-wifi.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-accessibility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -293,31 +310,31 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-system-time.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-time.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-device-info.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-device-manager.md -zh-cn/application-dev/reference/apis/js-apis-geolocation.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-geolocation.md @RayShih zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-power.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-power.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-sensor.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-thermal.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-update.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.mdd @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-vibrator.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen @@ -349,24 +366,84 @@ zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease -zh-cn/application-dev/quick-start/start-overview.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang -zh-cn/application-dev/quick-start/package-structure.md @RayShih -zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih -zh-cn/application-dev/quick-start/syscap.md @RayShih -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/apis/js-apis-buffer.md @zengyawen -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/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/Readme-CN.md @zengyawen -zh-cn/application-dev/file-management/ @qinxiaowang \ No newline at end of file +zh-cn/application-dev/reference/apis/js-apis-buffer.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 +zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bytrace.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationResult.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-dispatchInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-errorManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-inputevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-keycode.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-keyevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-logs.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-nfcController.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfctech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-pointer.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-app.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-device.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-file.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-location.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-network.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-notification.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-package.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-request.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-timer.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-touchevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zengyawen +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/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 6ddf26b87022c8bf098efc72de9ae4b4c0e28779..da1a7e1c517f284037a41a88e2167b6d1d2406aa 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -12,7 +12,7 @@ To use related APIs, you must declare the **ohos.permission.INTERNET** permissio For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). -The following table describes the related APIs. +The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). | API | Description | | ----------------------------------------- | --------------------------------------------------------- | diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md index aa619c4549083521dd6ac5bcc05795074adc9af4..a26f0c5a7003a14c13cf4fc697e3a55a202f1eec 100644 --- a/en/application-dev/device/device-location-overview.md +++ b/en/application-dev/device/device-location-overview.md @@ -15,15 +15,18 @@ Your application can call location-specific APIs to obtain the location informat Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - **Coordinate** + A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - **GNSS positioning** GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - **Base station positioning** + Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - **WLAN or Bluetooth positioning** + WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index d51625ccb9605fe2fb35b95f71eebc4e1607b753..eb023f7c782d8cb0e086819904b6def65da14214 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -38,7 +38,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat // Import the USB API package. import usb from '@ohos.usb'; // Obtain the USB device list. - var deviceList = usb.getDevices(); + let deviceList = usb.getDevices(); /* Example deviceList structure [ @@ -81,21 +81,21 @@ You can set a USB device as the USB host to connect to other USB devices for dat number: 1, type: 3, interfaceId: 0, - }, - ], - }, - ], - }, - ], - }, - ], + } + ] + } + ] + } + ] + } + ] */ ``` 2. Obtain the device operation permissions. ```js - var deviceName = deviceList[0].name; + let deviceName = deviceList[0].name; // Request the permissions to operate a specified device. usb.requestRight(deviceName).then(hasRight => { console.info("usb device request right result: " + hasRight); @@ -108,7 +108,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ```js // Open the device, and obtain the USB device pipe for data transfer. - var pipe = usb.connectDevice(deviceList[0]); + let pipe = usb.connectDevice(deviceList[0]); /* Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. @@ -127,7 +127,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { if (dataLength >= 0) { console.info("usb readData result Length : " + dataLength); - var resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. + let resultStr = this.ab2str(dataUint8Array); // Convert uint8 data into a string. console.info("usb readData buffer : " + resultStr); } else { console.info("usb readData failed : " + dataLength); diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 48f725e080441281cd2e88820eeacc6032a2dbab..afda67ee6fdf21b3d91d525d397c956d98167e82 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -12,12 +12,10 @@ The following table provides only a brief description of related APIs. For detai **Table 1** APIs for application event logging -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | -| write(string eventName, EventType type, object keyValues): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | -| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.| -| write(AppEventInfo info): Promise\ | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.| +| API | Description | +| ------------------------------------------------------------ | ---------------------------------------------------- | +| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| +| write(AppEventInfo info): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | When an asynchronous callback is used, the return value can be processed directly in the callback. @@ -84,6 +82,7 @@ The following uses a one-time event watcher as an example to illustrate the deve .fontWeight(FontWeight.Bold) Button("1 writeTest").onClick(()=>{ + // Perform event logging based on the input event parameters. hiAppEvent.write({ domain: "test_domain", name: "test_event", @@ -100,6 +99,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("2 addWatcherTest").onClick(()=>{ + // Add an event watcher based on the input subscription parameters. hiAppEvent.addWatcher({ name: "watcher1", appEventFilters: [{ domain: "test_domain" }], @@ -109,17 +109,23 @@ The following uses a one-time event watcher as an example to illustrate the deve timeOut: 2 }, onTrigger: function (curRow, curSize, holder) { + // If the holder object is null, return an error after recording it in the log. if (holder == null) { console.error("HiAppEvent holder is null"); return; } + // Set the size threshold to 1,000 bytes for obtaining an event package. + holder.setSize(1000); let eventPkg = null; + // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. while ((eventPkg = holder.takeNext()) != null) { - console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); - console.info("HiAppEvent eventPkg.row=" + eventPkg.row); - console.info("HiAppEvent eventPkg.size=" + eventPkg.size); + // Parse the obtained event package and display the result on the Log page. + console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId); + console.info('HiAppEvent eventPkg.row=' + eventPkg.row); + console.info('HiAppEvent eventPkg.size=' + eventPkg.size); + // Traverse and parse event string arrays in the obtained event package. for (const eventInfo of eventPkg.data) { - console.info("HiAppEvent eventPkg.data=" + eventInfo); + console.info('HiAppEvent eventPkg.data=' + eventInfo); } } } @@ -127,6 +133,7 @@ The following uses a one-time event watcher as an example to illustrate the deve }) Button("3 removeWatcherTest").onClick(()=>{ + // Remove the specified event watcher. hiAppEvent.removeWatcher({ name: "watcher1" }) diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index dc45ed9db0eec504b1ff6f535babf11265f2df91..c0b69b85a868f8afd7a7f627fb0275f46cbc87fc 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,19 +1,15 @@ # FAQs - [Ability Framework Development](faqs-ability.md) -- [Data Management Development](faqs-data-management.md) -- [File Management Development](faqs-file-management.md) -- [Graphics and Image Development](faqs-graphics.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (eTS) Development](faqs-ui-ets.md) - [Graphics and Image Development](faqs-graphics.md) - [File Management Development](faqs-file-management.md) +- [Network and Connection Development](faqs-connectivity.md) - [Data Management Development](faqs-data-management.md) - [Device Management Development](faqs-device-management.md) - [Native API Usage](faqs-native.md) -- [Network and Connection Development](faqs-connectivity.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) +- [hdc_std Command Usage](faqs-ide.md) +- [IDE Usage](faqs-hdc-std.md) - [Development Board](faqs-development-board.md) - diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index 3b8dea82129c03f0dc12c12296a28b9a0c46c99b..e3b02269e2de947fb4ab4069f1d7ba4812825ddc 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -19,7 +19,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available. +Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) 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/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index 280efd8afa5fa845dab0d607ed94b33e2a75e6d3..bf16d91435bf68ebd6f93a1a52b5f6da35e67169 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -4,5 +4,6 @@ - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) +- [Using MindSpore Lite for Model Inference](native-window-guidelines.md) diff --git a/en/application-dev/napi/figures/01.png b/en/application-dev/napi/figures/01.png new file mode 100644 index 0000000000000000000000000000000000000000..5293e5afe5a8637dbef3fd0b32c7bd43d60e4368 Binary files /dev/null and b/en/application-dev/napi/figures/01.png differ diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..47ede475575484d60317e9ed7e2afe586fb12524 --- /dev/null +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -0,0 +1,216 @@ +# Using MindSpore Lite for Model Inference + +## When to Use + +MindSpore Lite is an AI engine that provides AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition. + +This document describes the general development process for MindSpore Lite model inference. + +## Basic Concepts + +Before getting started, you need to understand the following basic concepts: + +**Tensor**: a special data structure that is similar to arrays and matrices. It is a basic data structure used in MindSpore Lite network operations. + +**Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. + + + +## Available APIs +APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. +### Context APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| +|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| +|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| +|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| +|void OH_AI_ContextAddDeviceInfo(OH_AI_ContextHandle context, OH_AI_DeviceInfoHandle device_info)|Adds a runtime device information object.| + +### Model APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_ModelHandle OH_AI_ModelCreate()|Creates a model object.| +|OH_AI_Status OH_AI_ModelBuildFromFile(OH_AI_ModelHandle model, const char *model_path,OH_AI_ModelType odel_type, const OH_AI_ContextHandle model_context)|Loads and builds a MindSpore model from a model file.| +|void OH_AI_ModelDestroy(OH_AI_ModelHandle *model)|Destroys a model object.| + +### Tensor APIs + +| API | Description | +| ------------------ | ----------------- | +|OH_AI_TensorHandleArray OH_AI_ModelGetInputs(const OH_AI_ModelHandle model)|Obtains the input tensor array structure of a model.| +|int64_t OH_AI_TensorGetElementNum(const OH_AI_TensorHandle tensor)|Obtains the number of tensor elements.| +|const char *OH_AI_TensorGetName(const OH_AI_TensorHandle tensor)|Obtains the name of a tensor.| +|OH_AI_DataType OH_AI_TensorGetDataType(const OH_AI_TensorHandle tensor)|Obtains the tensor data type.| +|void *OH_AI_TensorGetMutableData(const OH_AI_TensorHandle tensor)|Obtains the pointer to variable tensor data.| + +## How to Develop +The following figure shows the development process for MindSpore Lite model inference. + +**Figure 1** Development process for MindSpore Lite model inference +![how-to-use-mindspore-lite](figures/01.png) + +The development process consists of the following main steps: + +1. Prepare the required model. + + The required model can be downloaded directly or obtained using the model conversion tool. + + - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + +2. Create a context, and set parameters such as the number of runtime threads and device type. + + ```c + // Create a context, and set the number of runtime threads to 2 and the thread affinity mode to 1 (big cores first). + OH_AI_ContextHandle context = OH_AI_ContextCreate(); + if (context == NULL) { + printf("OH_AI_ContextCreate failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + const int thread_num = 2; + OH_AI_ContextSetThreadNum(context, thread_num); + OH_AI_ContextSetThreadAffinityMode(context, 1); + // Set the device type to CPU, and disable Float16 inference. + OH_AI_DeviceInfoHandle cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU); + if (cpu_device_info == NULL) { + printf("OH_AI_DeviceInfoCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + OH_AI_DeviceInfoSetEnableFP16(cpu_device_info, false); + OH_AI_ContextAddDeviceInfo(context, cpu_device_info); + ``` + +3. Create, load, and build the model. + + Call **OH_AI_ModelBuildFromFile** to load and build the model. + + In this example, the **argv[1]** parameter passed to **OH_AI_ModelBuildFromFile** indicates the specified model file path. + + ```c + // Create a model. + OH_AI_ModelHandle model = OH_AI_ModelCreate(); + if (model == NULL) { + printf("OH_AI_ModelCreate failed.\n"); + OH_AI_ContextDestroy(&context); + return OH_AI_STATUS_LITE_ERROR; + } + + // Load and build the model. The model type is OH_AI_ModelTypeMindIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +4. Input data. + + Before executing model inference, you need to populate data to the input tensor. In this example, random data is used to populate the model. + + ```c + // Obtain the input tensor. + OH_AI_TensorHandleArray inputs = OH_AI_ModelGetInputs(model); + if (inputs.handle_list == NULL) { + printf("OH_AI_ModelGetInputs failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + // Use random data to populate the tensor. + ret = GenerateInputDataWithRandom(inputs); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("GenerateInputDataWithRandom failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +5. Execute model inference. + + Call **OH_AI_ModelPredict** to perform model inference. + + ```c + // Execute model inference. + OH_AI_TensorHandleArray outputs; + ret = OH_AI_ModelPredict(model, inputs, &outputs, NULL, NULL); + if (ret != OH_AI_STATUS_SUCCESS) { + printf("OH_AI_ModelPredict failed, ret: %d.\n", ret); + OH_AI_ModelDestroy(&model); + return ret; + } + ``` + +6. Obtain the output. + + After model inference is complete, you can obtain the inference result through the output tensor. + + ```c + // Obtain the output tensor and print the information. + for (size_t i = 0; i < outputs.handle_num; ++i) { + OH_AI_TensorHandle tensor = outputs.handle_list[i]; + int64_t element_num = OH_AI_TensorGetElementNum(tensor); + printf("Tensor name: %s, tensor size is %zu ,elements num: %lld.\n", OH_AI_TensorGetName(tensor), + OH_AI_TensorGetDataSize(tensor), element_num); + const float *data = (const float *)OH_AI_TensorGetData(tensor); + printf("output data is:\n"); + const int max_print_num = 50; + for (int j = 0; j < element_num && j <= max_print_num; ++j) { + printf("%f ", data[j]); + } + printf("\n"); + } + ``` + +7. Destroy the model. + + If the MindSpore Lite inference framework is no longer needed, you need to destroy the created model. + + ```c + // Destroy the model. + OH_AI_ModelDestroy(&model); + ``` + +## Verification + +1. Compile **CMakeLists.txt**. + + ```cmake + cmake_minimum_required(VERSION 3.14) + project(Demo) + + add_executable(demo main.c) + + target_link_libraries( + demo + mindspore-lite.huawei + pthread + dl + ) + ``` + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + + - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. + +2. Run the CMake tool. + + - Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board. + - Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command: + + ```shell + ./demo mobilenetv2.ms + ``` + + The inference is successful if the output is similar to the following: + + ```shell + # ./QuickStart ./mobilenetv2.ms + Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. + output data is: + 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 + ``` 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/notification/common-event.md b/en/application-dev/notification/common-event.md index 37d55ef434d0cec71eed60862e13f1de0d9e13fb..dfb611ea572b80486756faaa4b004513cd6858a7 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). ```js -private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Used to save the created subscriber object for subsequent subscription and unsubscription. +private subscriber = null // Subscriber information var subscribeInfo = { diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md index b1df6ce3e2c022accb06bc1070740b7d7b3e7433..75237412fdf29d88843a9f23fa653f64f2de7c86 100644 --- a/en/application-dev/notification/notification-brief.md +++ b/en/application-dev/notification/notification-brief.md @@ -1,6 +1,6 @@ # Common Event and Notification Overview -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information. +The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. 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-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 9dc3ec0c3c5f022d4aecd438f59ebc830a34ae63..3d93bdf33a527668c4c1c98ac4cfd8611ea9010a 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -294,6 +294,9 @@ Registers an observer to listen for the state changes of all applications. }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -335,6 +338,9 @@ Registers an observer to listen for the state changes of a specified application }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } var bundleNameList = ['bundleName1', 'bundleName2']; @@ -707,6 +713,18 @@ Called when the application state changes. var applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -734,8 +752,20 @@ Called when the ability state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, onAbilityStateChanged(abilityStateData) { console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -762,8 +792,20 @@ Called when a process is created. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, onProcessCreated(processData) { console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -790,8 +832,20 @@ Called when a process is terminated. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, onProcessDied(processData) { console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); } } const observerCode = app.registerApplicationStateObserver(applicationStateObserver); @@ -818,6 +872,18 @@ Called when the process state changes. ```js var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, onProcessStateChanged(processData) { console.log('------------ onProcessStateChanged -----------', processData); } 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-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index eb85e5d52d50068b8147c1a4789389b2cf5506e1..d744a5ab3e1ef6770d0dee18d68c4a1512cd4183 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,40 +1,40 @@ # BundleInfo +The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - ## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | | extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| @@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------------- | ---- | ---- | -------------------- | +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId9+ | number | Yes | Yes | ID of the reason for requesting the permission.| @@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------- | -------------- | ---- | ---- | ------------------------- | +| Name | Type | Readable| Writable| Description | +| --------- | -------------- | ---- | ---- | --------------------------- | | abilities | Array\ | Yes | Yes | Abilities that use the permission.| | when | string | Yes | Yes | Time when the permission is used. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..323d4d1f948d12193b38333a11f7954153fec97a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PackInfo.md @@ -0,0 +1,157 @@ +# PackInfo + +The **PackInfo** module provides the bundle package information, which can be obtained using [bundle.getBundlePackInfo](js-apis-Bundle.md). + +> **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. + +## BundlePackFlag + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Value | Description | +| ------------------ | ---------- | ---------------------------------- | +| GET_PACK_INFO_ALL | 0x00000000 | All information about the package. | +| GET_PACKAGES | 0x00000001 | Package information about the package.| +| GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary of the package. | +| GET_MODULE_SUMMARY | 0x00000004 | Module summary of the package. | + +## BundlePackInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------- | --------------------------------------- | ---- | ---- | ----------------------------- | +| packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information. | +| summary | [PackageSummary](#packagesummary) | Yes | No | Package summary.| + +## PackageConfig + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| deviceType | Array\ | Yes | No | Device types supported. | +| name | string | Yes | No | Package name. | +| moduleType | string | Yes | No | Module type. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| + +## PackageSummary + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | --------------------------------------------- | ---- | ---- | -------------------- | +| app | [BundleConfigInfo](#bundleconfiginfo) | Yes | No | Bundle configuration information. | +| modules | Array\<[ModuleConfigInfo](#moduleconfiginfo)> | Yes | No | Module configuration information.| + +## BundleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | ---------------------------------- | +| bundleName | string | Yes | No | Bundle name of an application. It uniquely identifies the application.| +| version | [Version](#version) | Yes | No | Bundle version. | + +## ModuleConfigInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- | +| apiVersion | [ApiVersion](#apiversion) | Yes | No | API version of the module. | +| deviceType | Array\ | Yes | No | Device type of the module. | +| distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | +| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | +| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | Yes | No | Extension ability information of the module.| + +## ModuleDistroInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | +| mainAbility | string | Yes | No | Name of the main ability. | +| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| +| installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.| +| moduleName | string | Yes | No | Module name. | +| moduleType | string | Yes | No | Module type. | + +## ModuleAbilityInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Logical name of the ability. The name must be unique in the application. | +| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| +| visible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.| +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | + +## ExtensionAbilities + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Specification of the widget. A widget is a brief view of an application that is embedded on the home screen to receive periodical updates.| + +## AbilityFormInfo + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Widget name. | +| type | string | Yes | No | Widget type. | +| updateEnabled | boolean | Yes | No | Whether the widget supports periodical update. The value **true** means that the widget supports periodical update, and **false** means the opposite.| +| scheduledUpdateTime | string | Yes | No | Scheduled time to update the widget. The value is in 24-hour format and accurate to the minute. | +| updateDuration | number | Yes | No | Interval to update the widget. The unit is 30 minutes. The value is a multiple of 30. A widget can be updated periodically, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). If both are configured, **updateDuration** takes precedence.| +| supportDimensions | Array\ | Yes | No | Dimensions of the widget. The value can be **1\*2**, **2\*2**, **2\*4**, **4\*4**, or a combination of these options. At least one option must be specified when defining the widget.| +| defaultDimension | number | Yes | No | Default dimensions of the widget. The value must be available in the **supportDimensions** array of the widget.| + +## ApiVersion + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------------- | +| releaseType | string | Yes | No | Name of the API version. | +| compatible | number | Yes | No | Minimum API version.| +| target | numbe | Yes | No | Target API version. | + +## Version + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| minCompatibleVersionCode | number | Yes | No | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario. The value is a 32-bit non-negative integer.| +| name | string | Yes | No | Application version number visible to users. | +| code | number | Yes | No | Application version number used only for application management. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 5ea820e6160af090dbaf1e784970adfcb01ba013..ab561f552758ed5af3c79bc2c4406d84ceb56f2b 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -827,7 +827,7 @@ call.reject(1, (error, data) => { ## call.reject7+ -reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void +reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback\): void Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 9168a42e978c20caaface2523337d8c413a2296e..b4f3906b02b1dea7dabd558173010a37e65c2c19 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,6 +1,6 @@ # Standard NFC Card Emulation -The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. +The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). > **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. @@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul import cardEmulation from '@ohos.nfc.cardEmulation'; ``` +## FeatureType + +Enumerates the NFC card emulation types. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| HCE | 0 | HCE.| +| UICC | 1 | Subscriber identity module (SIM) card emulation.| +| ESE | 2 | embedded Secure Element (eSE) emulation.| ## cardEmulation.isSupported @@ -19,23 +30,31 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).| + **Return value** | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ -Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. +Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. ### startHCE8+ startHCE(aidList: string[]): boolean -Starts HCE. +Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -45,13 +64,13 @@ Starts HCE. | Name | Type | Mandatory| Description | | ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| +| aidList | string[] | Yes | AID list to register.| ### stopHCE8+ stopHCE(): boolean -Stops HCE. +Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -61,7 +80,7 @@ Stops HCE. on(type: "hceCmd", callback: AsyncCallback): void; -Subscribes to messages from the peer device after **startHCE()**. +Registers a callback to receive APDUs from the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------------- | | type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | -| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| +| callback | AsyncCallback | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| ### sendResponse8+ sendResponse(responseApdu: number[]): void; -Sends a response to the peer device. +Sends a response to the peer card reader. **Required permissions**: ohos.permission.NFC_CARD_EMULATION @@ -88,16 +107,25 @@ Sends a response to the peer device. | Name | Type | Mandatory| Description | | ------------ | -------- | ---- | -------------------------------------------------- | -| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| +| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js +import cardEmulation from '@ohos.nfc.cardEmulation'; + +var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE); +if (!isHceSupported) { + console.log('this device is not supported for HCE, ignore it.'); + return; +} + +// The device supports HCE and transimits APDUs with the remote NFC reader. var hceService = new cardEmulation.HceService(); hceService.startHCE([ "F0010203040506", "A0000000041010" -]) -hceService.stopHCE(); +]); + hceService.on("hceCmd", (err, res) => { if(err.data === 0) { console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); @@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => { console.log('callback => Operation hceCmd failed. Cause: ' + err.data); } }) + +// Stop HCE when the application exits the NFC card emulation. +hceService.stopHCE(); ``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50fad38058530104fda01f09d5745c0f8051000a..4cb3ef3bc5f1672b883ae42d722e593aabf03d24 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -18,7 +18,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v **System capability**: SystemCapability.Notification.CommonEvent -| Name | Value | Subscriber Permission | Description | +| Name | Value | Subscriber Permission | Description | | ------------ | ------------------ | ---------------------- | -------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | @@ -152,17 +152,17 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | | COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device becomes unmountable. | -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | @@ -170,13 +170,14 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | | COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | | COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | ## CommonEvent.publish publish(event: string, callback: AsyncCallback\): void -Publishes a common event. This API uses a callback to return the result. +Publishes a common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -209,7 +210,7 @@ CommonEvent.publish("event", PublishCallBack); publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes. This API uses a callback to return the result. +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -226,7 +227,7 @@ Publishes a common event with given attributes. This API uses a callback to retu ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. data: "initial data";// Result data of the common event. isOrdered: true // The common event is an ordered one. @@ -251,7 +252,7 @@ CommonEvent.publish("event", options, PublishCallBack); publishAsUser(event: string, userId: number, callback: AsyncCallback\): void -Publishes a common event to a specific user. This API uses a callback to return the result. +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -278,7 +279,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); @@ -290,7 +291,7 @@ CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void -Publishes a common event with given attributes to a specific user. This API uses a callback to return the result. +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -310,9 +311,9 @@ Publishes a common event with given attributes to a specific user. This API uses ```js // Attributes of a common event. -var options = { +let options = { code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event + data: "initial data";// Result data of the common event. } // Callback for common event publication @@ -325,7 +326,7 @@ function PublishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); @@ -337,7 +338,7 @@ CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void -Creates a subscriber. This API uses a callback to return the result. +Creates a subscriber. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -352,10 +353,10 @@ Creates a subscriber. This API uses a callback to return the result. ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -397,10 +398,10 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -419,7 +420,7 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void -Subscribes to common events. This API uses a callback to return the result. +Subscribes to common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -433,10 +434,10 @@ Subscribes to common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -471,7 +472,7 @@ CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void -Unsubscribes from common events. This API uses a callback to return the result. +Unsubscribes from common events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -485,10 +486,10 @@ Unsubscribes from common events. This API uses a callback to return the result. **Example** ```js -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; @@ -535,7 +536,7 @@ CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); getCode(callback: AsyncCallback\): void -Obtains the result code of this common event. This API uses a callback to return the result. +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -548,7 +549,7 @@ Obtains the result code of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code obtaining of an ordered common event. function getCodeCallback(err, Code) { @@ -578,7 +579,7 @@ Obtains the result code of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getCode().then((Code) => { console.info("getCode " + JSON.stringify(Code)); @@ -591,7 +592,7 @@ subscriber.getCode().then((Code) => { setCode(code: number, callback: AsyncCallback\): void -Sets the result code for this common event. This API uses a callback to return the result. +Sets the result code for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -605,7 +606,7 @@ Sets the result code for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code setting of an ordered common event. function setCodeCallback(err) { @@ -641,7 +642,7 @@ Sets the result code for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); @@ -654,7 +655,7 @@ subscriber.setCode(1).then(() => { getData(callback: AsyncCallback\): void -Obtains the result data of this common event. This API uses a callback to return the result. +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -667,7 +668,7 @@ Obtains the result data of this common event. This API uses a callback to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data obtaining of an ordered common event. function getDataCallback(err, Data) { @@ -697,7 +698,7 @@ Obtains the result data of this common event. This API uses a promise to return **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getData().then((Data) => { console.info("getData " + JSON.stringify(Data)); @@ -710,7 +711,7 @@ subscriber.getData().then((Data) => { setData(data: string, callback: AsyncCallback\): void -Sets the result data for this common event. This API uses a callback to return the result. +Sets the result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -724,7 +725,7 @@ Sets the result data for this common event. This API uses a callback to return t **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event function setDataCallback(err) { @@ -760,7 +761,7 @@ Sets the result data for this common event. This API uses a promise to return th **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); @@ -773,7 +774,7 @@ subscriber.setData("publish_data_changed").then(() => { setCodeAndData(code: number, data: string, callback:AsyncCallback\): void -Sets the result code and result data for this common event. This API uses a callback to return the result. +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -788,7 +789,7 @@ Sets the result code and result data for this common event. This API uses a call **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result code and result data setting of an ordered common event. function setCodeDataCallback(err) { @@ -825,7 +826,7 @@ Sets the result code and result data for this common event. This API uses a prom **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); @@ -838,7 +839,8 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { isOrderedCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is an ordered one. This API uses a callback to return the result. +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -851,7 +853,7 @@ Checks whether this common event is an ordered one. This API uses a callback to **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. function isOrderedCallback(err, isOrdered) { @@ -870,6 +872,7 @@ isOrderedCommonEvent(): Promise\ Checks whether this common event is an ordered one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -881,7 +884,7 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); @@ -894,7 +897,8 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { isStickyCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is a sticky one. This API uses a callback to return the result. +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + **System capability**: SystemCapability.Notification.CommonEvent @@ -907,7 +911,7 @@ Checks whether this common event is a sticky one. This API uses a callback to re **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. function isStickyCallback(err, isSticky) { @@ -926,6 +930,7 @@ isStickyCommonEvent(): Promise\ Checks whether this common event is a sticky one. This API uses a promise to return the result. + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -937,7 +942,7 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); @@ -950,7 +955,7 @@ subscriber.isStickyCommonEvent().then((isSticky) => { abortCommonEvent(callback: AsyncCallback\): void -Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a callback to return the result. +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -963,7 +968,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for common event aborting. function abortCallback(err) { @@ -993,7 +998,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); @@ -1006,7 +1011,7 @@ subscriber.abortCommonEvent().then(() => { clearAbortCommonEvent(callback: AsyncCallback\): void -Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a callback to return the result. +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1019,7 +1024,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. function clearAbortCallback(err) { @@ -1049,7 +1054,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); @@ -1062,7 +1067,7 @@ subscriber.clearAbortCommonEvent().then(() => { getAbortCommonEvent(callback: AsyncCallback\): void -Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a callback to return the result. +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1075,7 +1080,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. function getAbortCallback(err, AbortCommonEvent) { @@ -1105,7 +1110,7 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); @@ -1118,7 +1123,7 @@ subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { getSubscribeInfo(callback: AsyncCallback\): void -Obtains the subscriber information. This API uses a callback to return the result. +Obtains the subscriber information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1131,7 +1136,7 @@ Obtains the subscriber information. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. function getSubscribeInfoCallback(err, SubscribeInfo) { @@ -1161,7 +1166,7 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); @@ -1174,7 +1179,7 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { finishCommonEvent(callback: AsyncCallback\): void -Finishes this ordered common event. This API uses a callback to return the result. +Finishes this ordered common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1187,7 +1192,7 @@ Finishes this ordered common event. This API uses a callback to return the resul **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. function finishCommonEventCallback(err) { @@ -1217,7 +1222,7 @@ Finishes this ordered common event. This API uses a promise to return the result **Example** ```js -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index 67b846c17b94a6acee894da72ae28cedefd2532c..a166781108683f6b6fb53673da4deacd99882b26 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -202,8 +202,8 @@ Updates a contact based on the specified contact information and attributes. Thi contact.updateContact({ name: {fullName: 'xxx'}, phoneNumbers: [{phoneNumber: '138xxxxxxxx'}] - },{ - attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] + }, { + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err) => { if (err) { console.log('updateContact callback: err->${JSON.stringify(err)}'); @@ -432,7 +432,7 @@ Queries my card based on the specified contact attributes. This API uses an asyn ```js contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }, (err, data) => { if (err) { console.log(`queryMyCard callback: err->${JSON.stringify(err)}`); @@ -469,7 +469,7 @@ Queries my card based on the specified contact attributes. This API uses a promi ```js let promise = contact.queryMyCard({ - attributes:['ATTR_EMAIL', 'ATTR_NAME'] + attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME] }); promise.then((data) => { console.log(`queryMyCard success: data->${JSON.stringify(data)}`); @@ -487,7 +487,7 @@ Selects a contact. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Parameters** @@ -516,7 +516,7 @@ Selects a contact. This API uses a promise to return the result. **Permission required**: ohos.permission.READ_CONTACTS -**System capability**: SystemCapability.Applications.ContactsData +**System capability**: SystemCapability.Applications.Contacts **Return Value** diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 6398b87f685e5f91c59dacb1da97b4ad993e5afa..0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -16,19 +16,6 @@ import emitter from '@ohos.events.emitter' None -## EventPriority - -Enumerates the event emit priority levels. - -**System capability**: SystemCapability.Notification.Emitter - -| Name | Value | Description | -| --------- | ---- | ------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | -| HIGH | 1 | The event will be emitted before low-priority events. | -| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | -| IDLE | 3 | The event will be emitted after all the other events. | - ## emitter.on on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void @@ -39,21 +26,21 @@ Subscribes to an event in persistent manner. This API uses a callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('callback'); -}; -emitter.on(innerEvent, callback); +} +emitter.on(innerEvent, EmitterCallback); ``` ## emitter.once @@ -66,21 +53,21 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------ | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | --------------------------------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The **EventPriority** settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | **Example** ```javascript -var innerEvent = { +let innerEvent = { eventId: 1 }; -var callback = (eventData) => { +function EmitterCallback(eventData) { console.info('once callback'); }; -emitter.once(innerEvent, callback); +emitter.once(innerEvent, EmitterCallback); ``` ## emitter.off @@ -121,18 +108,31 @@ Emits an event to the event queue. **Example** ```javascript -var eventData = { +let eventData = { data: { "content": "c", "id": 1, }}; -var innerEvent = { +let innerEvent = { eventId: 1, priority: emitter.EventPriority.HIGH }; emitter.emit(innerEvent, eventData); ``` +## EventPriority + +Enumerates the event emit priority levels. + +**System capability**: SystemCapability.Notification.Emitter + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.| +| IDLE | 3 | The event will be emitted after all the other events. | + ## InnerEvent Describes an in-process event. @@ -141,7 +141,7 @@ Describes an in-process event. | Name | Type | Readable| Writable| Description | | -------- | ------------------------------- | ---- | ---- | ---------------------------------- | -| eventId | number | Yes | Yes | Event ID, which is used to identify an event.| +| eventId | number | Yes | Yes | Event ID.| | priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData 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-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index cc7d684666b28555597b406fddfc7b4c5cd7e130..aefc93a933ecdf42a0d270134d81f17c8a5788af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -3,6 +3,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,11 +19,11 @@ Before using application event logging, you need to understand the requirements **Event Domain** -An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). **Event Type** @@ -32,7 +33,7 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). - The parameter value is a string, number, boolean, or array. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -404,12 +405,30 @@ Defines a subscription data holder for processing subscription events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent +### constructor9+ + +constructor(watcherName: string); + +A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + ### setSize9+ setSize(size: number): void Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js @@ -425,6 +444,8 @@ takeNext(): [AppEventPackage](#appeventpackage9) Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 469fcae6f1c0f82f0894422b3e2a4416fabc7a60..53af9c42a3aa2d8cddf8d38290f7a29c30f8f9d6 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,6 +1,7 @@ # HiDebug -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. @@ -16,7 +17,7 @@ import hidebug from '@ohos.hidebug'; getNativeHeapSize(): bigint -Obtains the total size of the native heap memory. +Obtains the total size of the heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -26,84 +27,80 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. | Type | Description | | ------ | --------------------------- | -| bigint | Total size of the native heap memory, in kB.| +| bigint | Total size of the heap memory of this application, in kB.| **Example** - -```js -let nativeHeapSize = hidebug.getNativeHeapSize(); -``` + ```js + let nativeHeapSize = hidebug.getNativeHeapSize(); + ``` ## hidebug.getNativeHeapAllocatedSize getNativeHeapAllocatedSize(): bigint -Obtains the size of the allocated native heap memory. +Obtains the size of the allocated heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | --------------------------------- | -| bigint | Size of the allocated native heap memory, in kB.| +| bigint | Size of the allocated heap memory of this application, in kB.| **Example** - -```js -let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); -``` + ```js + let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); + ``` ## hidebug.getNativeHeapFreeSize getNativeHeapFreeSize(): bigint -Obtains the size of the free native heap memory. +Obtains the size of the free heap memory of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------------- | -| bigint | Size of the free native heap memory, in kB.| +| bigint | Size of the free heap memory of this application, in kB.| **Example** - -```js -let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); -``` + ```js + let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); + ``` ## hidebug.getPss getPss(): bigint -Obtains the PSS of this process. +Obtains the size of the used physical memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | ------------------------- | -| bigint | PSS of the process, in kB.| +| bigint | Used physical memory of this process, in kB.| **Example** - -```js -let pss = hidebug.getPss(); -``` + ```js + let pss = hidebug.getPss(); + ``` ## hidebug.getSharedDirty @@ -114,18 +111,17 @@ Obtains the size of the shared dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the shared dirty memory of the process, in kB.| +| bigint | Size of the shared dirty memory of this process, in kB.| **Example** - -```js -let sharedDirty = hidebug.getSharedDirty(); -``` + ```js + let sharedDirty = hidebug.getSharedDirty(); + ``` ## hidebug.getPrivateDirty9+ @@ -135,11 +131,11 @@ Obtains the size of the private dirty memory of this process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| bigint | Size of the private dirty memory of the process, in kB.| +| bigint | Size of the private dirty memory of this process, in kB.| **Example** @@ -157,18 +153,17 @@ For example, if the CPU usage is **50%**, **0.5** is returned. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -**Return value** +**Return value** | Type | Description | | ------ | -------------------------- | -| number | CPU usage of the process.| +| number | CPU usage of this process.| **Example** - -```js -let cpuUsage = hidebug.getCpuUsage(); -``` + ```js + let cpuUsage = hidebug.getCpuUsage(); + ``` ## hidebug.startProfiling @@ -195,6 +190,7 @@ hidebug.stopProfiling(); ``` + ## hidebug.stopProfiling stopProfiling() : void @@ -225,7 +221,7 @@ Exports data from the specified heap file. | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** @@ -250,7 +246,6 @@ This is a system API and cannot be called by third-party applications. | serviceid | number | Yes | ID of the system service. | **Return value** - | Type | Description | | ------ | -------------------------- | | string | Absolute path of the file that contains the service information to dump. | diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 65952c0b23946b02582d74e5be9fbc5f8c33b42d..553ff5a9925a30f262acb49bb69cd4e95c7bd95b 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -2,7 +2,7 @@ Provides system event logging APIs for system HAP applications. -> **NOTE**
+> **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. @@ -19,7 +19,7 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | FAULT | 1 | Error event.| | STATISTIC | 2 | Statistic event.| @@ -32,7 +32,7 @@ Defines a system event. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -50,7 +50,7 @@ Writes event information to the event file. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | | info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| @@ -91,13 +91,13 @@ Writes event information to the event file. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory| Description| +| Name | Type | Mandatory | Description| | --------- | ----------------------- | ---- | --------------- | | info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** -| Type | Description | +| Type | Description | | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| @@ -138,7 +138,7 @@ Enumerates matching rule types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Default Value| Description| +| Name | Default Value | Description | | -------- | -------- | -------- | | WHOLE_WORD | 1 | Whole word matching.| | PREFIX | 2 | Prefix matching.| @@ -150,7 +150,7 @@ Defines rules for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -163,7 +163,7 @@ Defines a watcher for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| @@ -181,7 +181,7 @@ Adds a watcher for event subscription. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -223,7 +223,7 @@ Removes a watcher used for event subscription. **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory | Description | | ------ | ------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| @@ -260,7 +260,7 @@ Defines arguments for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | beginTime | number | Yes| Start time (13-digit timestamp) for event query.| | endTime | number | Yes| End time (13-digit timestamp) for event query.| @@ -272,7 +272,7 @@ Defines rules for event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | names | string[] | Yes| Array of event names.| @@ -283,7 +283,7 @@ Defines an event query instance. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| @@ -300,7 +300,7 @@ Queries system events. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory | Description | | ------ | ----------------------------- | ---- | ------------------------ | | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 9e0e0bf5160d01596d0c6e0969c3cc783712f45a..294ed0fa79032d4e47e6c9c999183811d272acd3 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -358,7 +358,7 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | +| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.8+ | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | @@ -432,7 +432,7 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 2d66bc9c61a54f3bfa88d6e7f27aa93fabd49a2d..a886b6c643be1295bd49f0bf166d1e244d82f9af 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -12,1218 +12,2277 @@ The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by app ```js import huks from '@ohos.security.huks' ``` -## HuksErrorCode -Enumerates the error codes. +## HuksParam -**System capability**: SystemCapability.Security.Huks +Defines the **param** in the **properties** array of **options** used in the APIs. -| Name | Value | Description| -| -------------------------- | ----- | ---- | -| HUKS_SUCCESS | 0 |Success.| -| HUKS_FAILURE | -1 |Failure.| -| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| -| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| -| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| -| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| -| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| -| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| -| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| -| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| -| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.| -| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| -| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| -| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| -| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| -| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| -| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| -| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| -| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| -| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| -| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| -| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| -| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| -| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| -| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| -| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| -| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| -| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| -| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| -| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| -| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| -| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| -| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| -| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| -| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| -| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| -| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| -| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| -| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| -| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| -| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| -| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| -| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. | -| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.| -| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.| -| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.| -| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.| -| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.| -| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.| -| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.| -| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.| -| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.| -| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.| -| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.| -| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| -| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| -| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.| -| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.| -| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.| -| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.| -| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| -| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| -| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| -| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| -| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| -| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.| -| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.| -| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| -| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| -| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| -| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| -| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| +**System capability**: SystemCapability.Security.Huks +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------ | +| tag | [HuksTag](#hukstag) | Yes | Tag. | +| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| -## HuksKeyPurpose +## HuksOptions -Enumerates the key purposes. +Defines the **options** used in the APIs. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------ | ---- | -------------------------------- | -| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt plaintext.| -| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| -| HUKS_KEY_PURPOSE_SIGN | 4 | Used to sign data. | -| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signed data. | -| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | -| HUKS_KEY_PURPOSE_WRAP | 32 | Used to wrap a key. | -| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used to unwrap a key. | -| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | -| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | ------------------------ | +| properties | Array\<[HuksParam](#huksparam)> | No | Properties used to hold the **HuksParam** array.| +| inData | Uint8Array | No | Input data. | -## HuksKeyDigest +## HuksSessionHandle9+ -Enumerates the digest algorithms. +Defines the HUKS handle structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_DIGEST_NONE | 0 | No digest algorithm| -| HUKS_DIGEST_MD5 | 1 | MD5| -| HUKS_DIGEST_SM39+ | 2 | SM3| -| HUKS_DIGEST_SHA1 | 10 | SHA1| -| HUKS_DIGEST_SHA224 | 11 | SHA-224| -| HUKS_DIGEST_SHA256 | 12 | SHA-256| -| HUKS_DIGEST_SHA384 | 13 | SHA-384| -| HUKS_DIGEST_SHA512 | 14 | SHA-512| +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ---------------------------------------------------- | +| handle | number | Yes | Value of the handle. | +| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| -## HuksKeyPadding +## HuksReturnResult9+ -Enumerates the padding algorithms. +Defines the **HuksResult** structure. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------- | ---- | ---------------------------------------- | -| HUKS_PADDING_NONE | 0 | No padding algorithm| -| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| -| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| -| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5| -| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS) #5| -| HUKS_PADDING_PKCS7 | 5 | PKCS #7| -## HuksCipherMode -Enumerates the cipher modes. +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ---------------- | +| outData | Uint8Array | No | Output data. | +| properties | Array\<[HuksParam](#huksparam)> | No | Property information. | +| certChains | Array\ | No | Certificate chain information.| -**System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode| -| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| -| HUKS_MODE_CTR | 3 | Counter (CTR) mode| -| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| -| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| -| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| +## huks.generateKeyItem9+ -## HuksKeySize +generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key sizes. +Generates a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------- | ---- | ------------------------------------------ | -| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | -| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | -| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | -| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | -| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | -| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | -| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits | -| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | -| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | -| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | -| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | -| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | -| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | -| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| -| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits | -| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | -| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | -| HUKS_SM2_KEY_SIZE_2569+ | 256 | SM2 key of 256 bits | -| HUKS_SM4_KEY_SIZE_1289+ | 128 | SM4 key of 128 bits | +**Parameters** -## HuksKeyAlg +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the key algorithms. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------- | ---- | --------------------- | -| HUKS_ALG_RSA | 1 | RSA | -| HUKS_ALG_ECC | 2 | ECC | -| HUKS_ALG_DSA | 3 | DSA | -| HUKS_ALG_AES | 20 | AES | -| HUKS_ALG_HMAC | 50 | HMAC | -| HUKS_ALG_HKDF | 51 | HKDF | -| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | -| HUKS_ALG_ECDH | 100 | ECDH | -| HUKS_ALG_X25519 | 101 | X25519 | -| HUKS_ALG_ED25519 | 102 | ED25519| -| HUKS_ALG_DH | 103 | DH | -| HUKS_ALG_SM29+ | 150 | SM2 | -| HUKS_ALG_SM39+ | 151 | SM3 | -| HUKS_ALG_SM49+ | 152 | SM4 | +## huks.generateKeyItem9+ -## HuksKeyGenerateType +generateKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the key generation types. +Generates a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ------------------------------ | ---- | ---------------- | -| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| -| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| -| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| +**Parameters** -## HuksKeyFlag +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| -Enumerates the key generation modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +try { + huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------------- | ---- | ------------------------------------ | -| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using an API. | -| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using an API. | -| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using a key agreement API.| -| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is derived by using an API.| +## huks.deleteKeyItem9+ -## HuksKeyStorageType +deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Enumerates the key storage modes. +Deletes a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ----------------------- | ---- | ------------------------------ | -| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | -| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| +**Parameters** -## HuksSendType +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| -Enumerates the tag transfer modes. +**Example** -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: deleteKeyItem key success`); + } + }); +} catch (error) { + console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| -------------------- | ---- | ----------------- | -| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| -| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| +## huks.deleteKeyItem9+ -## HuksUnwrapSuite9+ +deleteKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Enumerates the algorithm suites used when a wrapped key is imported. +Deletes a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| ---------------------------------------------- | ---- | ----------------------------------------------------- | -| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| -| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | - -## HuksImportKeyType9+ +**Parameters** -Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| ------------------------- | ---- | ------------------------------ | -| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | -| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | -| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| - -## HuksUserAuthType9+ - -Enumerates the user authentication types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------- | -| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | -| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| -| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| - -## HuksAuthAccessType9+ - -Enumerates the access control types. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| --------------------------------------- | ---- | ------------------------------------------------ | -| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key is invalid after the password is cleared. | -| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key is invalid after a new biometric feature is added.| - -## HuksChallengeType9+ - -Enumerates the types of the challenges generated when a key is used. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| -| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| -| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| - -## HuksChallengePosition9+ - -Enumerates the positions of the 8-byte valid value in a custom challenge generated. - -**System capability**: SystemCapability.Security.Huks - -| Name | Value | Description | -| ------------------------------- | ---- | ------------------------------ | -| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23 indicate the valid challenge of the key.| -| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31 indicate the valid challenge of the key.| - -## HuksSecureSignType9+ - -Defines the signature type of the key generated or imported. - -**System capability**: SystemCapability.Security.Huks +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.deleteKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: deleteKeyItem key success`); + }) + .catch(error => { + console.error(`promise: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` -| Name | Value | Description | -| ------------------------------ | ---- | ------------------------------------------------------------ | -| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used to sign data, the data will be added with the authentication information and then be signed.| +## huks.getSdkVersion -## HuksTagType +getSdkVersion(options: HuksOptions) : string -Enumerates the tag data types. +Obtains the SDK version of the current system. **System capability**: SystemCapability.Security.Huks +**Parameters** -| Name | Value | Description | -| --------------------- | ------- | --------------------------------------- | -| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | -| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | -| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| -| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | -| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | -| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | +| Name | Type | Mandatory| Description | +| ------- | ---------- | ---- | ------------------------- | +| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| -## HuksTag +**Return value** -Enumerates the tags used to invoke parameters. +| Type | Description | +| ------ | ------------- | +| string | SDK version obtained.| -**System capability**: SystemCapability.Security.Huks +**Example** -| Name | Value | Description | -| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | -| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | -| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.| -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | -| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +```js +/* Set options to emptyOptions. */ +let emptyOptions = { + properties: [] +}; +let result = huks.getSdkVersion(emptyOptions); +``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Generates a key. This API uses an asynchronous callback to return the result. +Imports a key in plaintext. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code defined in **HuksResult** will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Generate an RSA key of 512 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_OAEP + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var options = { - properties: properties +let options = { + properties: properties, + inData: plainTextSize32 }; -huks.generateKey(keyAlias, options, function (err, data){}); +try { + huks.importKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: importKeyItem success`); + } + }); +} catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.generateKey +## huks.importKeyItem9+ -generateKey(keyAlias: string, options: HuksOptions) : Promise\ +importKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Generates a key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------ | -| keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| - -**Return value** - -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Example** ```js -/* Generate an ECC key of 256 bits. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES }; properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 }; properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 }; -var options = { - properties: properties +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB }; -var result = huks.generateKey(keyAlias, options); +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +try { + huks.importKeyItem(keyAlias, huksoptions) + .then ((data) => { + console.info(`promise: importKeyItem success`); + }) + .catch(error => { + console.error(`promise: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Deletes a key. This API uses an asynchronous callback to return the result. +Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated. | -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + huks.attestKeyItem(aliasString, options, function (error, data) { + if (error) { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: attestKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.deleteKey +## huks.attestKeyItem9+ -deleteKey(keyAlias: string, options: HuksOptions) : Promise\ +attestKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Deletes a key. This API uses a promise to return the result. +Obtains the certificate used to verify a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ----------------------------------------------------- | -| keyAlias | string | Yes | Key alias passed in when the key was generated.| -| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | --------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { - properties: [] -}; -var result = huks.deleteKey(keyAlias, emptyOptions); +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + try { + await huks.generateKeyItem(alias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + await generateKey(aliasString); + try { + await huks.attestKeyItem(aliasString, options) + .then ((data) => { + console.info(`promise: attestKeyItem success`); + }) + .catch(error => { + console.error(`promise: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} ``` -## huks.getSdkVersion +## huks.importWrappedKeyItem9+ -getSdkVersion(options: HuksOptions) : string +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the SDK version of the current system. +Imports a wrapped key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------- | ---- | ------------------------- | -| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| - -**Return value** - -| Type | Description | -| ------ | ------------- | -| string | SDK version obtained.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** ```js -/* Set options to emptyOptions. */ -var emptyOptions = { - properties: [] +import huks from '@ohos.security.huks'; + +let exportWrappingKey; +let alias1 = "importAlias"; +let alias2 = "wrappingKeyAlias"; + +async function TestGenFunc(alias, options) { + try { + await genKey(alias, options) + .then((data) => { + console.info(`callback: generateKeyItem success`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function genKey(alias, options) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestExportFunc(alias, options) { + try { + await exportKey(alias, options) + .then ((data) => { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportWrappingKey = data.outData; + }) + .catch(error => { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function exportKey(alias, options) : Promise { + return new Promise((resolve, reject) => { + try { + huks.exportKeyItem(alias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await importWrappedKey(alias, wrappingAlias, options) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKey(alias, wrappingAlias, options) { + return new Promise((resolve, reject) => { + try { + huks.importWrappedKeyItem(alias, wrappingAlias, options, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw(error); + } + }); +} + +async function TestImportWrappedKeyFunc( + alias, + wrappingAlias, + genOptions, + importOptions +) { + await TestGenFunc(wrappingAlias, genOptions); + await TestExportFunc(wrappingAlias, genOptions); + + /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. + * For example, import **keyA**. + * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. + * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. + * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. + * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, **aad2**, ciphertext **kek_enc**, and encrypted **tag2**. + * 5. Generate the **importOptions.inData** field in the following format: + * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + + * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + + * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + + * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + + * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc + */ + let inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); + importOptions.inData = inputKey; + await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +} + +function makeGenerateOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, + }; + let options = { + properties: properties + }; + return options; }; -var result = huks.getSdkVersion(emptyOptions); + +function makeImportOptions() { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING + }; + let options = { + properties: properties + }; + return options; +}; + +function huksImportWrappedKey() { + let genOptions = makeGenerateOptions(); + let importOptions = makeImportOptions(); + TestImportWrappedKeyFunc( + alias1, + alias2, + genOptions, + importOptions + ); +} ``` -## huks.importKey +## huks.importWrappedKeyItem9+ -importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses an asynchronous callback to return the result. +Imports a wrapped key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| ---------------- | --------------------------- | ---- | --------------------------------------------- | +| keyAlias | string | Yes | Alias of the wrapped key to import. | +| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| **Example** ```js -/* Import an AES key of 256 bits. */ -var plainTextSize32 = makeRandomArr(32); -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); +/* The process is similar as if a callback is used, except the following:*/ +async function TestImportWrappedFunc(alias, wrappingAlias, options) { + try { + await huks.importWrappedKeyItem(alias, wrappingAlias, options) + .then ((data) => { + console.info(`promise: importWrappedKeyItem success`); + }) + .catch(error => { + console.error(`promise: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - return arr; -}; -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: -huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var options = { - properties: properties, - inData: plainTextSize32 +} +``` + +## huks.exportKeyItem9+ + +exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -huks.importKey(keyAlias, options, function (err, data){}); +try { + huks.exportKeyItem(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.importKey +## huks.exportKeyItem9+ -importKey(keyAlias: string, options: HuksOptions) : Promise\ +exportKeyItem(keyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses a promise to return the result. +Exports a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key to import.| -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ---------------------------------------------- | ------------------------------------------------------------ | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js -/* Import an AES key of 128 bits. */ -var plainTextSize32 = makeRandomArr(32); - -function makeRandomArr(size) { - var arr = new Uint8Array(size); - for (var i = 0; i < size; i++) { - arr[i] = Math.floor(Math.random() * 10); - } - return arr; -}; - -/* Step 1 Generate a key. */ -var keyAlias = 'keyAlias'; -var properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB -}; -var huksoptions = { - properties: properties, - inData: plainTextSize32 +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] }; -var result = huks.importKey(keyAlias, huksoptions); +try { + huks.exportKeyItem(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: exportKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} ``` -## huks.attestkey9+ +## huks.getKeyItemProperties9+ -attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +getKeyItemProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Obtains the certificate used to verify a key. This API uses an asynchronous callback to return the result. +Obtains key properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.error(`callback: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + } + }); +} catch (error) { + console.error(`callback: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.getKeyItemProperties9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +getKeyItemProperties(keyAlias: string, options: HuksOptions) : Promise\ - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; +Obtains key properties. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------- | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If **err** is not returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.getKeyItemProperties(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: getKeyItemProperties success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: getKeyItemProperties failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: getKeyItemProperties input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options, function (err, data) { - printLog(`key attest result : ${JSON.stringify(data)}`); - }); +## huks.isKeyItemExist9+ + +isKeyItemExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------- | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions, function (error, data) { + if (error) { + console.info(`callback: isKeyItemExist success, data = ${JSON.stringify(data)}`); + } else { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -## huks.attestkey9+ +## huks.isKeyItemExist9+ -attestKey(keyAlias: string, options: HuksOptions) : Promise\ +isKeyItemExist(keyAlias: string, options: HuksOptions) : Promise\ -Obtains the certificate used to verify a key. This API uses a promise to return the result. +Checks whether a key exists. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key to check. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| **Return value** -| Type | Description | -| ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js -let securityLevel = stringToUint8Array('sec_level'); -let challenge = stringToUint8Array('challenge_data'); -let versionInfo = stringToUint8Array('version_info'); -let keyAliasString = "key attest"; - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +try { + huks.isKeyItemExist(keyAlias, emptyOptions) + .then ((data) => { + console.info(`promise: isKeyItemExist success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + }); +} catch (error) { + console.error(`promise: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } +``` -function printLog(...data) { - console.error(data.toString()); -} +## huks.initSession9+ -async function generateKey(alias) { - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; +initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void - await huks.generateKey(alias, options).then(async (data) => { - console.error(`generateKey data ${JSON.stringify(data)}`); - }).catch((err) => { - console.error(`generateKey err: " + ${JSON.stringify(err)}`); - });; -} +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. -async function attestKey() { - let aliasString = keyAliasString; - let aliasUint8 = stringToUint8Array(aliasString); - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let options = { - properties: properties - }; - await generateKey(aliasString); - huks.attestKey(aliasString, options) - .then((data) => { - console.log(`test attestKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test attestKey information: ' + JSON.stringify(err)); - }); -} -``` +**System capability**: SystemCapability.Security.Huks -## huks.importWrappedKey9+ +**Parameters** -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | +| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| -Imports a wrapped key. This API uses an asynchronous callback to return the result. + +## huks.initSession9+ + +initSession(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes the data for a key operation. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------------ | +| keyAlias | string | Yes | Alias of the target key. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | Yes | Token of the **Update** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.updateSession9+ + +updateSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Updates the key operation data by segment. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | -------------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | Yes | Token for the **Finish** operation. | +| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| + + +## huks.finishSession9+ + +finishSession(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.initSession**, **huks.updateSession**, and **huks.finishSession** must be used together. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------- | ---- | ----------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | +| token | Uint8Array | No | Token for the **Finish** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| + + +## huks.abortSession9+ + +abortSession(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js -var exportWrappingKey; -var alias1 = "importAlias"; -var alias2 = "wrappingKeyAlias"; - -async function TestGenFunc(alias, options) { - await genKey(alias, options) - .then((data) => { - console.log(`test genKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test genKey err information: ' + JSON.stringify(err)); - }); +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function genKey(alias, options) { - return new Promise((resolve, reject) => { - huks.generateKey(alias, options, function (err, data) { - console.log(`test genKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test genKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) +}; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } + + try { + await huks.generateKeyItem(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: generateKeyItem success`); + } + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestExportFunc(alias, options) { - await exportKey(alias, options) - .then((data) => { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test exportKey err information: ' + JSON.stringify(err)); - }); +async function huksInit() { + console.log('enter huksInit'); + try { + huks.initSession(keyAlias, options, function (error, data) { + if (error) { + console.error(`callback: initSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + } + }); + } catch (error) { + console.error(`callback: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function exportKey(alias, options) { - return new Promise((resolve, reject) => { - huks.exportKey(alias, options, function (err, data) { - console.log(`test exportKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('test exportKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - exportWrappingKey = data.outData; - resolve(data); - } - }); - }); +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + huks.updateSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: updateSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: updateSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - await importWrappedKey(alias, wrappingAlias, options) - .then((data) => { - console.log(`TestImportWrappedFunc data: ${JSON.stringify(data)}`); - }) - .catch((err) => { - console.log('test importWrappedKey err information: ' + JSON.stringify(err)); - }); +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + huks.finishSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: finishSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: finishSession success, data = ${JSON.stringify(data)}`); + } + }); + } catch (error) { + console.error(`callback: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function importWrappedKey(alias, wrappingAlias, options) { - return new Promise((resolve, reject) => { - huks.importWrappedKey(alias, wrappingAlias, options, function (err, data) { - console.log(`importWrappedKey data: ${JSON.stringify(data)}`); - if (err.code !== 0) { - console.log('importWrappedKey err information: ' + JSON.stringify(err)); - reject(err); - } else { - resolve(data); - } - }); - }); +async function huksAbort() { + console.log('enter huksAbort'); + try { + huks.abortSession(handle, options, function (error, data) { + if (error) { + console.error(`callback: abortSession failed, code: ${error.code}, msg: ${error.message}`); + } else { + console.info(`callback: abortSession success`); + } + }); + } catch (error) { + console.error(`callback: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } +``` -async function TestImportWrappedKeyFunc( - alias, - wrappingAlias, - genOptions, - importOptions -) { - await TestGenFunc(wrappingAlias, genOptions); - await TestExportFunc(wrappingAlias, genOptions); +## huks.abortSession9+ - /*The following operations do not invoke the HUKS APIs, and the specific implementation is not provided here. - * For example, import **keyA**. - * 1. Use ECC to generate a public and private key pair **keyB**. The public key is **keyB_pub**, and the private key is **keyB_pri**. - * 2. Use **keyB_pri** and the public key obtained from **wrappingAlias** to negotiate the shared key **share_key**. - * 3. Randomly generate a key **kek** and use it to encrypt **keyA** with AES-GCM. During the encryption, record **nonce1**, **aad1**, ciphertext **keyA_enc**, and encrypted **tag1**. - * 4. Use **share_key** to encrypt **kek** with AES-GCM. During the encryption, record **nonce2**, ** aad2**, ciphertext **kek_enc**, and encrypted **tag2**. - * 5. Generate the **importOptions.inData** field in the following format: - * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + - * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + - * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + - * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + - * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc - */ - var inputKey = new Uint8Array([0x02, 0x00, 0x00, 0x00]); - importOptions.inData = inputKey; - await TestImportWrappedFunc(alias, wrappingAlias, importOptions); +abortSession(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation. | +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation. | + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +/* huks.initSession, huks.updateSession, and huks.finishSession must be used together. + * If an error occurs in any of huks.initSession, huks.updateSession, + * and huks.finishSession operation, + * huks.abortSession must be called to terminate the use of the key. + * + * The following uses the callback of an RSA1024 key as an example. + */ +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + let tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; } -function makeGenerateOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - var options = { - properties: properties - }; - return options; +let keyAlias = "HuksDemoRSA"; +let properties = new Array(); +let options = { + properties: properties, + inData: new Uint8Array(0) }; +let handle; +async function generateKey() { + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, + } -function makeImportOptions() { - var properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING - }; - var options = { - properties: properties - }; - return options; + try { + await huks.generateKeyItem(keyAlias, options) + .then((data) => { + console.info(`promise: generateKeyItem success`); + }) + .catch(error => { + console.error(`promise: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksInit() { + console.log('enter huksInit'); + try { + await huks.initSession(keyAlias, options) + .then ((data) => { + console.info(`promise: initSession success, data = ${JSON.stringify(data)}`); + handle = data.handle; + }) + .catch(error => { + console.error(`promise: initSession key failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: initSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksUpdate() { + console.log('enter huksUpdate'); + options.inData = stringToUint8Array("huksHmacTest"); + try { + await huks.updateSession(handle, options) + .then ((data) => { + console.info(`promise: updateSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: updateSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: updateSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksFinish() { + console.log('enter huksFinish'); + options.inData = new Uint8Array(0); + try { + await huks.finishSession(handle, options) + .then ((data) => { + console.info(`promise: finishSession success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`promise: finishSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: finishSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +async function huksAbort() { + console.log('enter huksAbort'); + try { + await huks.abortSession(keyAlias, options) + .then ((data) => { + console.info(`promise: abortSession success`); + }) + .catch(error => { + console.error(`promise: abortSession failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`promise: abortSession input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} +``` + + +## HuksExceptionErrCode9+ + +Enumerates the error codes. + +For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcode-huks.md). + +**System capability**: SystemCapability.Security.Huks + +| Name | Description | Error Code | +| ---------------------------------------------- | --------------------------- | -------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | +| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | +| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | +| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | + +## HuksKeyPurpose + +Enumerates the key purposes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | Used to encrypt the plaintext.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | Used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | Used for signing. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | Used to verify the signature. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | Used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | Used for an encrypted export. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | Used for an encrypted import. | +| HUKS_KEY_PURPOSE_MAC | 128 | Used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | Used for key agreement. | + +## HuksKeyDigest + +Enumerates the digest algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_DIGEST_NONE | 0 | No digest algorithm| +| HUKS_DIGEST_MD5 | 1 | MD5| +| HUKS_DIGEST_SM39+ | 2 | SM3| +| HUKS_DIGEST_SHA1 | 10 | SHA-1| +| HUKS_DIGEST_SHA224 | 11 | SHA-224| +| HUKS_DIGEST_SHA256 | 12 | SHA-256| +| HUKS_DIGEST_SHA384 | 13 | SHA-384| +| HUKS_DIGEST_SHA512 | 14 | SHA-512| + +## HuksKeyPadding + +Enumerates the padding algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_PADDING_NONE | 0 | No padding algorithm| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP)| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS)| +| HUKS_PADDING_PKCS1_V1_5 | 3 | Public Key Cryptography Standards (PKCS) #1 v1.5| +| HUKS_PADDING_PKCS5 | 4 | PKCS #5| +| HUKS_PADDING_PKCS7 | 5 | PKCS #7| + +## HuksCipherMode + +Enumerates the cipher modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------- | ---- | --------------------- | +| HUKS_MODE_ECB | 1 | Electronic Code Block (ECB) mode| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode| + +## HuksKeySize + +Enumerates the key sizes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------- | ---- | ------------------------------------------ | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits | +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits | +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits | +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits | +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits | +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits | +| HUKS_ECC_KEY_SIZE_224 | 224 | Elliptic Curve Cryptography (ECC) key of 224 bits | +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits | +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | +| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | +| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| +| HUKS_DH_KEY_SIZE_2048 | 2048 | Diffie-Hellman (DH) key of 2048 bits | +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits | +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits | +| HUKS_SM2_KEY_SIZE_2569+ | 256 | ShangMi2 (SM2) key of 256 bits | +| HUKS_SM4_KEY_SIZE_1289+ | 128 | ShangMi4 (SM4) key of 128 bits | + +## HuksKeyAlg + +Enumerates the key algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | --------------------- | +| HUKS_ALG_RSA | 1 | RSA | +| HUKS_ALG_ECC | 2 | ECC | +| HUKS_ALG_DSA | 3 | DSA | +| HUKS_ALG_AES | 20 | AES | +| HUKS_ALG_HMAC | 50 | HMAC | +| HUKS_ALG_HKDF | 51 | HKDF | +| HUKS_ALG_PBKDF2 | 52 | PBKDF2 | +| HUKS_ALG_ECDH | 100 | ECDH | +| HUKS_ALG_X25519 | 101 | X25519 | +| HUKS_ALG_ED25519 | 102 | ED25519| +| HUKS_ALG_DH | 103 | DH | +| HUKS_ALG_SM29+ | 150 | SM2 | +| HUKS_ALG_SM39+ | 151 | SM3 | +| HUKS_ALG_SM49+ | 152 | SM4 | + +## HuksKeyGenerateType + +Enumerates the key generation types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------- | +| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| +| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| +| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| + +## HuksKeyFlag + +Enumerates the key generation modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------ | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | Import a key using an API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | Generate a key by using an API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | Generate a key by using a key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | Derive a key by using an API.| + +## HuksKeyStorageType + +Enumerates the key storage modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ----------------------- | ---- | ------------------------------ | +| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | +| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| + +## HuksSendType + +Enumerates the tag transfer modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------- | ---- | ----------------- | +| HUKS_SEND_TYPE_ASYNC | 0 | The tag is sent asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | The tag is sent synchronously.| + +## HuksUnwrapSuite9+ + +Enumerates the algorithm suites required for encrypted imports. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------------------------- | ---- | ----------------------------------------------------- | +| HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING | 1 | Use X25519 for key agreement and then use AES-256 GCM to encrypt the key.| +| HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING | 2 | Use ECDH for key agreement and then use AES-256 GCM to encrypt the key. | + +## HuksImportKeyType9+ + +Enumerates the types of keys to import. By default, a public key is imported. This field is not required when a symmetric key is imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| HUKS_KEY_TYPE_PUBLIC_KEY | 0 | Public key | +| HUKS_KEY_TYPE_PRIVATE_KEY | 1 | Private key | +| HUKS_KEY_TYPE_KEY_PAIR | 2 | Public and private key pair| + +## HuksUserAuthType9+ + +Enumerates the user authentication types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------- | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. | +| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.| +| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.| + +## HuksAuthAccessType9+ + +Enumerates the access control types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.| + +## HuksChallengeType9+ + +Enumerates the types of the challenges generated when a key is used. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which is of 32 bytes by default.| +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one authentication for multiple keys.| +| HUKS_CHALLENGE_TYPE_NONE | 2 | Challenge is not required.| + +## HuksChallengePosition9+ + +Enumerates the positions of the 8-byte valid value in a custom challenge generated. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_POS_0 | 0 | Bytes 0 to 7.| +| HUKS_CHALLENGE_POS_1 | 1 | Bytes 8 to 15.| +| HUKS_CHALLENGE_POS_2 | 2 | Bytes 16 to 23.| +| HUKS_CHALLENGE_POS_3 | 3 | Bytes 24 to 31.| + +## HuksSecureSignType9+ + +Defines the signature type of the key generated or imported. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ------------------------------------------------------------ | +| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | The signature carries authentication information. This field is specified when a key is generated or imported. When the key is used for signing, the data will be added with the authentication information and then be signed.| + +## HuksTagType + +Enumerates the tag data types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | +| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | BigInt. | +| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | +| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | + +## HuksTag + +Enumerates the tags used to invoke parameters. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite required for encrypted imports. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | ID of the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | SN of the device. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | International mobile equipment identity (IMEI) of the device. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Mobile equipment identity (MEID) of the device. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Manufacturer of the device. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | System-on-a-chip (SoCID) of the device. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Unique device identifier (UDID) of the device. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security level used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. For details about other results, see HuksResult.| + +**Example** + +```js +/* Generate an RSA key of 512 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_OAEP +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +huks.generateKey(keyAlias, options, function (err, data){}); +``` + +## huks.generateKey(deprecated) + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Generate an ECC key of 256 bits. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +let options = { + properties: properties +}; +let result = huks.generateKey(keyAlias, options); +``` + + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey(deprecated) + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Set options to emptyOptions. */ +let keyAlias = 'keyAlias'; +let emptyOptions = { + properties: [] +}; +let result = huks.deleteKey(keyAlias, emptyOptions); +``` + + +## huks.importKey(deprecated) + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key in plaintext. This API uses an asynchronous callback to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| + +**Example** + +```js +/* Import an AES key of 256 bits. */ +let plainTextSize32 = makeRandomArr(32); +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; - -function huksImportWrappedKey() { - var genOptions = makeGenerateOptions(); - var importOptions = makeImportOptions(); - TestImportWrappedKeyFunc( - alias1, - alias2, - genOptions, - importOptions - ); -} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: +huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let options = { + properties: properties, + inData: plainTextSize32 +}; +huks.importKey(keyAlias, options, function (err, data){}); ``` -## huks.importWrappedKey9+ +## huks.importKey(deprecated) -importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ +importKey(keyAlias: string, options: HuksOptions) : Promise\ -Imports a wrapped key. This API uses a promise to return the result. +Imports a key in plaintext. This API uses a promise to return the result. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). **System capability**: SystemCapability.Security.Huks **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------------- | ---- | --------------------------------------------- | -| keyAlias | string | Yes | Alias of the wrapped key to import. | -| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Alias of the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| **Return value** | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs.| **Example** ```js -/* The process is similar as if a callback is used, except the following:*/ -async function TestImportWrappedFunc(alias, wrappingAlias, options) { - var result = await huks.importWrappedKey(alias, wrappingAlias, options); - if (result.errorCode === 0) { - console.log('test importWrappedKey success'); - } else { - console.log('test importWrappedKey fail'); - } -} +/* Import an AES key of 128 bits. */ +let plainTextSize32 = makeRandomArr(32); + +function makeRandomArr(size) { + let arr = new Uint8Array(size); + for (let i = 0; i < size; i++) { + arr[i] = Math.floor(Math.random() * 10); + } + return arr; +}; + +/* Step 1 Generate a key. */ +let keyAlias = 'keyAlias'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let huksoptions = { + properties: properties, + inData: plainTextSize32 +}; +let result = huks.importKey(keyAlias, huksoptions); ``` -## huks.exportKey + +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Exports a key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1232,25 +2291,27 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.exportKey(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.exportKey +## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions) : Promise\ Exports a key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1264,25 +2325,28 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.| +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **outData** contains the public key exported.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.exportKey(keyAlias, emptyOptions); +let result = huks.exportKey(keyAlias, emptyOptions); ``` -## huks.getKeyProperties + +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Obtains key properties. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1291,25 +2355,27 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If **errorCode** is **HUKS_SUCCESS**, the operation is successful. Otherwise, an error occurs.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.getKeyProperties +## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ Obtains key properties. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1323,25 +2389,28 @@ Obtains key properties. This API uses a promise to return the result. | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code will be returned. **properties** returns the parameters required for generating the key.| +| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. If **HUKS_SUCCESS** is returned, the operation is successful. Otherwise, an error occurs. **properties** returns the parameters required for generating the key.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.getKeyProperties(keyAlias, emptyOptions); +let result = huks.getKeyProperties(keyAlias, emptyOptions); ``` -## huks.isKeyExist + +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Checks whether a key exists. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1350,25 +2419,27 @@ Checks whether a key exists. This API uses an asynchronous callback to return th | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the key to check.| | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| -| callback | AsyncCallback\ | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); ``` -## huks.isKeyExist +## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ Checks whether a key exists. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1382,26 +2453,26 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists, and **FALSE** means the opposite.| **Example** ```js /* Set options to emptyOptions. */ -var keyAlias = 'keyAlias'; -var emptyOptions = { +let keyAlias = 'keyAlias'; +let emptyOptions = { properties: [] }; -var result = huks.isKeyExist(keyAlias, emptyOptions); +let result = huks.isKeyExist(keyAlias, emptyOptions); ``` - - -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Initializes the data for a key operation. This API uses an asynchronous callback to return the result. +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1411,14 +2482,16 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the initialization operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| -## huks.init +## huks.init(deprecated) init(keyAlias: string, options: HuksOptions) : Promise\ -Initializes the data for a key operation. This API uses a promise to return the result. +Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1428,52 +2501,21 @@ Initializes the data for a key operation. This API uses a promise to return the | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the initialization operation.| - - -## huks.update(deprecated) - -update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void - -Updates the key operation data by segment. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.update9+](#huksupdate9-1). - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| ## huks.update(deprecated) -update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ - -Updates the key operation data by segment. This API uses a promise to return the result. - -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9-2). - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| token | Uint8Array | No | Token of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - -## huks.update9+ - update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9). **System capability**: SystemCapability.Security.Huks @@ -1483,14 +2525,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| +## huks.update(deprecated) -## huks.update9+ +update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void -update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -Updates the key operation by segment. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). **System capability**: SystemCapability.Security.Huks @@ -1499,15 +2542,17 @@ Updates the key operation by segment. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | +| token | Uint8Array | No | Token of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| token | Uint8Array | Yes | Token of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| -## huks.update9+ +## huks.update(deprecated) update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Updates the key operation by segment. This API uses a promise to return the result. +Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). **System capability**: SystemCapability.Security.Huks @@ -1516,15 +2561,23 @@ Updates the key operation by segment. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ----------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| +| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -## huks.finish +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| + + +## huks.finish(deprecated) finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. +Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). **System capability**: SystemCapability.Security.Huks @@ -1534,14 +2587,16 @@ Completes the key operation and releases resources. This API uses an asynchronou | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| -## huks.finish +## huks.finish(deprecated) finish(handle: number, options: HuksOptions) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result. +Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. + +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). **System capability**: SystemCapability.Security.Huks @@ -1551,49 +2606,22 @@ Completes the key operation and releases resources. This API uses a promise to r | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void - -Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the operation result.| - - -## huks.finish9+ - -finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ - -Completes the key operation and releases resources. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.Huks +**Return value** -**Parameters** +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ----------------------------------- | -| handle | number | Yes | Handle of the **Finish** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | -| token | Uint8Array | No | Token for the **Finish** operation. | -| promise | Promise\<[HuksResult](#huksresult)> | Yes | Promise used to return the operation result.| -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void Aborts the use of the key. This API uses an asynchronous callback to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1602,7 +2630,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| **Example** @@ -1612,27 +2640,14 @@ Aborts the use of the key. This API uses an asynchronous callback to return the * * The following uses the callback of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; async function generateKey() { properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, @@ -1657,11 +2672,11 @@ async function generateKey() { huks.generateKey(keyalias, options); } function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } async function huksInit() { @@ -1708,112 +2723,16 @@ async function huksAbort() { }); console.log(resultMessage); } - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('Tocallback') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - routePage() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## huks.abort +## huks.abort(deprecated) abort(handle: number, options: HuksOptions) : Promise\; Aborts the use of the key. This API uses a promise to return the result. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). + **System capability**: SystemCapability.Security.Huks **Parameters** @@ -1822,7 +2741,12 @@ Aborts the use of the key. This API uses a promise to return the result. | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| **Example** @@ -1832,34 +2756,20 @@ Aborts the use of the key. This API uses a promise to return the result. * * The following uses the promise of an RSA 1024-bit key as an example. */ -import router from '@system.router'; -import huks from '@ohos.security.huks'; - -async function routePage() { - let options = { - uri: 'pages/second' - } - try { - await router.push(options) - } catch (err) { - console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`) - } -} - -var keyalias = "HuksDemoRSA"; -var properties = new Array(); -var options = { +let keyalias = "HuksDemoRSA"; +let properties = new Array(); +let options = { properties: properties, inData: new Uint8Array(0) }; -var handle; -var resultMessage = ""; +let handle; +let resultMessage = ""; function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); + let tmpUint8Array = new Uint8Array(arr); return tmpUint8Array; } @@ -1890,7 +2800,7 @@ async function huksInit() { return new Promise((resolve, reject) => { huks.init(keyalias, options, async function (err, data) { if (data.errorCode === 0) { - resultMessage = "Initialization successful!" + resultMessage = "init success!" handle = data.handle; } else { resultMessage = "init fail errorCode: " + data.errorCode @@ -1935,128 +2845,10 @@ function huksAbort() { }); }); } -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('to Promise') - .fontSize(20) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - router.back() - }) - Button() { - Text('generateKey') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - generateKey() - }) - Button() { - Text('Init') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksInit() - }) - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksUpdate() - }) - Button() { - Text('Finish') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksFinish() - }) - Button() { - Text('Abort') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('50%') - .height('10%') - .backgroundColor('#0D9FFB') - .onClick(() => { - huksAbort() - }) - } - .width('100%') - .height('100%') - } -} ``` -## HuksParam - -Defines the **param** in the **properties** array of **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------- | ---- | ------------ | -| tag | [HuksTag](#hukstag) | Yes | Tag. | -| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| - -## HuksOptions - -Defines the **options** used in the APIs. - -**System capability**: SystemCapability.Security.Huks - -| Name | Type | Mandatory| Description | -| ---------- | ----------------- | ---- | ------------------------ | -| properties | Array\<[HuksParam](#huksparam)> | No | Array used to hold **HuksParam**.| -| inData | Uint8Array | No | Input data. | -## HuksHandle +## HuksHandle(deprecated) Defines the HUKS handle structure. @@ -2069,7 +2861,7 @@ Defines the HUKS handle structure. | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| -## HuksResult +## HuksResult(deprecated) Defines the **HuksResult** structure. @@ -2083,3 +2875,87 @@ Defines the **HuksResult** structure. | outData | Uint8Array | No | Output data. | | properties | Array\<[HuksParam](#huksparam)> | No | Property information. | | certChains | Array\ | No | Certificate chain information.| + + +## HuksErrorCode(deprecated) + +Enumerates the error codes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description| +| -------------------------- | ----- | ---- | +| HUKS_SUCCESS | 0 |Success.| +| HUKS_FAILURE | -1 |Failure.| +| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| +| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| +| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| +| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| +| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| +| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| +| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| +| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failure.| +| HUKS_ERROR_STORAGE_FAILURE | -10 |Insufficient storage space.| +| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| +| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| +| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| +| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| +| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| +| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| +| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| +| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| +| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| +| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| +| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| +| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| +| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| +| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| +| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| +| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| +| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| +| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| +| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| +| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| +| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| +| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| +| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| +| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| +| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| +| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| +| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| +| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| +| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| +| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| +| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| +| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. | +| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.| +| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.| +| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to obtain the key purpose.| +| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to obtain the digest algorithm.| +| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to obtain the cipher mode.| +| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to obtain the nonce.| +| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to obtain the AAD.| +| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to obtain the initialization vector (IV).| +| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to obtain the AE flag.| +| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to obtain the salt value.| +| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to obtain the number of iterations.| +| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| +| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| +| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding algorithm.| +| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid key purpose.| +| HUKS_ERROR_INVALID_MODE | -116 |Invalid cipher mode.| +| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest algorithm.| +| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| +| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| +| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| +| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| +| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| +| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.| +| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.| +| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| +| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.| +| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.| +| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 866a5833b69feb01da451f2464fbdd7915f06172..6b7463a11b96f468bd275b0fd0fd841fe690713c 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('Failed to read image pixel data.'); // Called if no condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -392,7 +394,6 @@ Obtains pixel map information of this image. This API uses a promise to return t const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } image.createPixelMap(color, opts).then(pixelmap => { - globalpixelmap = pixelmap; if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -428,7 +429,6 @@ const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if (pixelmap == undefined) { - globalpixelmap = pixelmap; console.error("Failed to obtain the image pixel map information."); } pixelmap.getImageInfo((err, imageInfo) => { @@ -559,9 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - var rate = 0.5; - await pixelmap.opacity(rate); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -582,9 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -async function () { - await pixelmap.createAlphaPixelmap(); -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -632,7 +631,7 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -661,7 +660,7 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -685,7 +684,7 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -714,7 +713,7 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -737,7 +736,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -765,7 +764,7 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -789,7 +788,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -818,7 +817,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -841,7 +840,7 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -869,7 +868,7 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -891,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -920,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -1345,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1401,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1429,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1617,6 +1605,7 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1645,6 +1634,7 @@ Packs an image. This API uses a promise to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { @@ -1673,10 +1663,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1704,14 +1698,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -1764,7 +1762,7 @@ imagePackerApi.release().then(()=>{ createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver -Create an **ImageReceiver** instance by specifying the image width, height, format, and capacity. +Creates an **ImageReceiver** instance by specifying the image width, height, format, and capacity. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver @@ -1774,7 +1772,7 @@ Create an **ImageReceiver** instance by specifying the image width, height, form | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format. | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1955,7 +1953,7 @@ receiver.readNextImage().then(img => { }) ``` -### on('imageArrival')9+ +### on9+ on(type: 'imageArrival', callback: AsyncCallback\): void @@ -2020,6 +2018,228 @@ receiver.release().then(() => { }) ``` +## image.createImageCreator9+ + +createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator + +Creates an **ImageCreator** instance by specifying the image width, height, format, and capacity. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| width | number | Yes | Default image width. | +| height | number | Yes | Default image height. | +| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. | +| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------------- | +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| + +**Example** + +```js +var creator = image.createImageCreator(8192, 8, 4, 8); +``` + +## ImageCreator9+ + +Requests an image native data area, and provides APIs for applications to compile native image data. +Before calling any APIs in **ImageCreator**, you must create an **ImageCreator** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +| Name | Type | Readable| Writable| Description | +| -------- | ---------------------------- | ---- | ---- | ------------------ | +| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| +| format | [ImageFormat](#imageformat9) | Yes | No | Image format. | + +### dequeueImage9+ + +dequeueImage(callback: AsyncCallback\): void + +Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage((err, img) => { + if (err) { + console.info('dequeueImage succeeded.'); + } + console.info('dequeueImage failed.')); +}); +``` + +### dequeueImage9+ + +dequeueImage(): Promise\ + +Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| --------------- | ------------- | +| Promise\ | Promise used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage().then(img => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.log('dequeueImage failed: ' + error); +}) +``` + +### queueImage9+ + +queueImage(interface: Image, callback: AsyncCallback\): void + +Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| interface | Image | Yes | Drawn image.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img, (err) => { + if (err) { + console.info('dequeueImage failed: ' + err); + } + console.info('dequeueImage succeeded'); +}) +``` + +### queueImage9+ + +queueImage(interface: Image): Promise\ + +Places the drawn image in the dirty queue. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------| ---- | ------------------- | +| interface | Image | Yes | Drawn image.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img).then(() => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.info('dequeueImage failed: ' + error); +}) +``` + +### on9+ + +on(type: 'imageRelease', callback: AsyncCallback\): void + +Listens for image release events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| type | string | Yes | Type of event, which is **'imageRelease'**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.on('imageRelease', (err) => { + if (err) { + console.info('on faild' + err); + } + console.info('on succeeded'); +}) +``` + +### release9+ + +release(callback: AsyncCallback\): void + +Releases this **ImageCreator** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release((err) => { + if (err) { + console.info('release failed: ' + err); + } + console.info('release succeeded'); +}); +``` +### release9+ + +release(): Promise\ + +Releases this **ImageCreator** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release().then(() => { + console.info('release succeeded'); +}).catch(error => { + console.info('release failed'); +}) +``` + ## Image9+ Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called. @@ -2147,7 +2367,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo @@ -2159,6 +2379,7 @@ Describes image information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | | size | [Size](#size) | Yes | Yes | Image size.| +| density9+ | number | Yes | Yes | Pixel density, in ppi.| ## Size @@ -2181,8 +2402,13 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888. | -| BGRA_88889+ | 4 | BGRA_8888. | +| RGBA_8888 | 3 | RGBA_8888.| +| BGRA_88889+ | 4 | BGRA_8888.| +| RGB_8889+ | 5 | RGB_888. | +| ALPHA_89+ | 6 | ALPHA_8. | +| RGBA_F169+ | 7 | RGBA_F16. | +| NV219+ | 8 | NV21. | +| NV129+ | 9 | NV12. | ## AlphaType9+ @@ -2194,8 +2420,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2250,6 +2476,7 @@ Defines image decoding options. | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | number | Yes | Yes | Index of the image to decode. | +| fitDensity9+ | number | Yes | Yes | Image pixel density, in ppi. | ## Region7+ @@ -2260,7 +2487,7 @@ Describes region information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | | size | [Size](#size) | Yes | Yes | Region size. | -| x | number | Yes | Yes | X coordinate of the region.| +| x | number | Yes | Yes | X coordinate to translate.| | y | number | Yes | Yes | Y coordinate of the region.| ## PackingOption @@ -2271,8 +2498,9 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the JPEG and WebP formats are supported. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| +| bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| ## GetImagePropertyOptions7+ @@ -2299,8 +2527,14 @@ Describes the exchangeable image file format (EXIF) information of an image. | IMAGE_WIDTH | "ImageWidth" | Image width. | | GPS_LATITUDE | "GPSLatitude" | Image latitude. | | GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. | +| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.| +| SCENE_TYPE9+ | "SceneType" | Shooting scene mode, for example, portrait, scenery, motion, and night sight. | +| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | +| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | + ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 3c908fabdc24cccc6f5949c9d5add8da88a08d01..79cdf3ac5627984eba2f03e7eb37b9cc7137de4a 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -64,7 +64,7 @@ Creates a Locale object. | Name | Type | Mandatory | Description | | ------- | ------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options | LocaleOptions | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | **Example** ``` @@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | **Example** ``` @@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| **Example** ``` @@ -332,7 +332,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | **Example** ``` @@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| **Example** @@ -449,7 +449,7 @@ Creates a Collator object. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | **Example** ``` @@ -497,9 +497,10 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| **Example** + ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); @@ -552,7 +553,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | **Example** ``` @@ -634,7 +635,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ``` @@ -710,7 +711,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. | Type | Description | | ---------------------------------------- | --------------------------------- | -| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 50057062701f1ddbe0b058dc79e957c1a47e63a3..189042b1f1df1727423c65c0a226b11ae473db2a 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -42,18 +42,18 @@ Registers a listener to observe the mission status. **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - - ``` +``` ## missionManager.unregisterMissionListener @@ -77,21 +77,22 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { - console.log("unregisterMissionListener"); + console.log("unregisterMissionListener"); }) - ``` +``` ## missionManager.unregisterMissionListener @@ -120,21 +121,22 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** - ```js - var listener = { - onMissionCreated: function(mission){"--------onMissionCreated-------"}, - onMissionDestroyed: function(mission){"--------onMissionDestroyed-------"}, - onMissionSnapshotChanged: function(mission){"--------onMissionSnapshotChanged-------"}, - onMissionMovedToFront: function(mission){"--------onMissionMovedToFront-------"}, - onMissionIconUpdated: function(mission,icon){"--------onMissionIconUpdated-------"} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); - - missionManager.unregisterMissionListener(listenerid).catch(function (err){ - console.log(err); - }); - ``` +```js + var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + }; + console.log("registerMissionListener") + var listenerid = missionManager.registerMissionListener(listener); + + missionManager.unregisterMissionListener(listenerid).catch(function (err) { + console.log(err); + }); +``` ## missionManager.getMissionInfo diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 1d272e9f03c4956e141456324b1eb1f05293cea8..a0d7d5ccf282bb20fe549332e57e580ee3e52d7c 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -110,7 +110,7 @@ connection.hasDefaultNet().then(function (has) { getAllNets(callback: AsyncCallback<Array<NetHandle>>): void -Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. +Obtains the list of all connected networks. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -136,7 +136,7 @@ connection.getAllNets(function (error, nets) { getAllNets(): Promise<Array<NetHandle>> -Obtains the list of all active data networks. This API uses a promise to return the result. +Obtains the list of all connected networks. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -280,7 +280,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports connection of the data network. This API uses an asynchronous callback to return the result. +Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -308,7 +308,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -Reports connection of the data network. This API uses a promise to return the result. +Reports connection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -341,7 +341,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports disconnection of the data network. This API uses an asynchronous callback to return the result. +Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -369,7 +369,8 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle): Promise<void> -Reports disconnection of the data network. This API uses a promise to return the result. +Reports disconnection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. + **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -558,7 +559,7 @@ connection.disableAirplaneMode().then(function (error) { createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection -Obtains the handle of the network specified by **netSpecifier**. +Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used. **System capability**: SystemCapability.Communication.NetManager.Core @@ -950,9 +951,9 @@ Defines the network capability. | ------------------------ | ---- | ---------------------- | | NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| | NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| -| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| +| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.| | NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| -| NET_CAPABILITY_VALIDATED | 16 | The network is available. | +| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the network management module. | ## NetBearType diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index c8a9d7cf699963e494c5f04c1d5e887e8795eb0f..105af3cf95ca3a052faddbb6fe632940169fbcd1 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,6 +1,6 @@ # Standard NFC -The **nfcController** module implements Near-Field Communication (NFC). +The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,12 +12,24 @@ The **nfcController** module implements Near-Field Communication (NFC). import controller from '@ohos.nfc.controller'; ``` +## NfcState + +Enumerates the NFC states. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | NFC is closed (OFF).| +| STATE_TURNING_ON | 2 | NFC is turning on.| +| STATE_ON | 3 | NFC is open (ON).| +| STATE_TURNING_OFF | 4 | NFC is turning off.| ## controller.isNfcAvailable isNfcAvailable(): boolean -Checks whether NFC is available. +Checks whether the device supports NFC. **System capability**: SystemCapability.Communication.NFC.Core @@ -25,7 +37,7 @@ Checks whether NFC is available. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if NFC is available; returns **false** otherwise.| +| boolean | Returns **true** if the device supports NFC; returns **false** otherwise.| ## controller.openNfc @@ -42,7 +54,7 @@ Opens NFC. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## controller.closeNfc @@ -76,7 +88,7 @@ Checks whether NFC is open. ## controller.getNfcState -getNfcState(): NfcState +getNfcState(): [NfcState](#nfcstate) Obtains the NFC state. @@ -86,13 +98,13 @@ Obtains the NFC state. | **Type**| **Description** | | -------- | ---------------------- | -| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| +| [NfcState](#nfcstate) | NFC state obtained. For details, see [NfcState](#nfcstate).| ## controller.on('nfcStateChange') -on(type: "nfcStateChange", callback: Callback<NfcState>): void +on(type: "nfcStateChange", callback: Callback<[NfcState](#nfcstate)>): void -Subscribes to NFC state changes. +Subscribes to NFC state changes. A callback will be invoked to return the NFC state when the NFC state changes. **System capability**: SystemCapability.Communication.NFC.Core @@ -101,15 +113,15 @@ Subscribes to NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') -off(type: "nfcStateChange", callback?: Callback<NfcState>): void +off(type: "nfcStateChange", callback?: Callback<[NfcState](#nfcstate)>): void -Unsubscribes from the NFC state changes. +Unsubscribes from the NFC state changes. The subscriber will not receive NFC state change notifications. **System capability**: SystemCapability.Communication.NFC.Core @@ -118,35 +130,37 @@ Unsubscribes from the NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| -| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** ```js - import nfcController from '@ohos.nfcController'; - - var NFC_STATE_NOTIFY = "nfcStateChange"; - - var recvNfcStateNotifyFunc = result => { - console.info("nfc state receive state: " + result); + import controller from '@ohos.nfc.controller'; + + // Define a callback key. + var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; + + // Register the callback to receive NFC state change notifications. + controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); + } + }); + + // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); } - - // Subscribe to the NFC state changes. - nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - - // Unsubscribe from the NFC state changes. - nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - ``` - -## NfcState - -Enumerates the NFC states. -**System capability**: SystemCapability.Communication.NFC.Core + // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); + } -| Name| Default Value| Description| -| -------- | -------- | -------- | -| STATE_OFF | 1 | Off| -| STATE_TURNING_ON | 2 | Turning on| -| STATE_ON | 3 | On| -| STATE_TURNING_OFF | 4 | Turning off| + // Unregister the callback. + controller.off(NFC_STATE_CALLBACK_KEY); + ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 2f6cd9a66dcd1a5dcd1d92e126461e307643814f..ff80fc8564758868ec979ff6bf033b7084fea561 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -34,7 +34,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // NotificationRequest object var notificationRequest = { @@ -83,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -113,7 +117,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r ```js // publish callback function publishCallback(err) { - console.info("==========================>publishCallback=======================>"); + if (err.code) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } } // ID of the user who receives the notification var userId = 1 @@ -169,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("==========================>publishCallback=======================>"); + console.info("publish sucess"); }); ``` @@ -195,7 +203,11 @@ Cancels a notification with the specified ID and label. This API uses an asynchr ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, "label", cancelCallback) ``` @@ -221,7 +233,7 @@ Cancels a notification with the specified ID and label. This API uses a promise ```js Notification.cancel(0).then(() => { - console.info("==========================>cancelCallback=======================>"); + console.info("cancel sucess"); }); ``` @@ -247,7 +259,11 @@ Cancels a notification with the specified ID. This API uses an asynchronous call ```js // cancel callback function cancelCallback(err) { - console.info("==========================>cancelCallback=======================>"); + if (err.code) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } } Notification.cancel(0, cancelCallback) ``` @@ -273,7 +289,11 @@ Cancels all notifications. This API uses an asynchronous callback to return the ```js // cancel callback function cancelAllCallback(err) { - console.info("==========================>cancelAllCallback=======================>"); + if (err.code) { + console.info("cancelAll failed " + JSON.stringify(err)); + } else { + console.info("cancelAll success"); + } } Notification.cancelAll(cancelAllCallback) ``` @@ -292,7 +312,7 @@ Cancels all notifications. This API uses a promise to return the result. ```js Notification.cancelAll().then(() => { - console.info("==========================>cancelAllCallback=======================>"); + console.info("cancelAll sucess"); }); ``` @@ -322,7 +342,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } // NotificationSlot object var notificationSlot = { @@ -359,7 +383,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -385,7 +409,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ```js // addSlot callback function addSlotCallBack(err) { - console.info("==========================>addSlotCallBack=======================>"); + if (err.code) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } } Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) ``` @@ -410,7 +438,7 @@ Adds a notification slot. This API uses a promise to return the result. ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlot sucess"); }); ``` @@ -440,7 +468,11 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu ```js // addSlots callback function addSlotsCallBack(err) { - console.info("==========================>addSlotsCallBack=======================>"); + if (err.code) { + console.info("addSlots failed " + JSON.stringify(err)); + } else { + console.info("addSlots success"); + } } // NotificationSlot object var notificationSlot = { @@ -485,7 +517,7 @@ var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("==========================>addSlotCallback=======================>"); + console.info("addSlots sucess"); }); ``` @@ -511,7 +543,11 @@ Obtains a notification slot of the specified type. This API uses an asynchronous ```js // getSlot callback function getSlotCallback(err,data) { - console.info("==========================>getSlotCallback=======================>"); + if (err.code) { + console.info("getSlot failed " + JSON.stringify(err)); + } else { + console.info("getSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType, getSlotCallback) @@ -544,7 +580,7 @@ Obtains a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("==========================>getSlotCallback=======================>"); + console.info("getSlot sucess, data: " + JSON.stringify(data)); }); ``` @@ -569,7 +605,11 @@ Obtains all notification slots. This API uses an asynchronous callback to return ```js // getSlots callback function getSlotsCallback(err,data) { - console.info("==========================>getSlotsCallback=======================>"); + if (err.code) { + console.info("getSlots failed " + JSON.stringify(err)); + } else { + console.info("getSlots success"); + } } Notification.getSlots(getSlotsCallback) ``` @@ -594,7 +634,7 @@ Obtains all notification slots of this application. This API uses a promise to r ```js Notification.getSlots().then((data) => { - console.info("==========================>getSlotsCallback=======================>"); + console.info("getSlots sucess, data: " + JSON.stringify(data)); }); ``` @@ -620,7 +660,11 @@ Removes a notification slot of the specified type. This API uses an asynchronous ```js // removeSlot callback function removeSlotCallback(err) { - console.info("==========================>removeSlotCallback=======================>"); + if (err.code) { + console.info("removeSlot failed " + JSON.stringify(err)); + } else { + console.info("removeSlot success"); + } } var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType,removeSlotCallback) @@ -647,7 +691,7 @@ Removes a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("==========================>removeSlotCallback=======================>"); + console.info("removeSlot sucess"); }); ``` @@ -671,7 +715,11 @@ Removes all notification slots. This API uses an asynchronous callback to return ```js function removeAllCallBack(err) { - console.info("================>removeAllCallBack=======================>"); + if (err.code) { + console.info("removeAllSlots failed " + JSON.stringify(err)); + } else { + console.info("removeAllSlots success"); + } } Notification.removeAllSlots(removeAllCallBack) ``` @@ -690,7 +738,7 @@ Removes all notification slots. This API uses a promise to return the result. ```js Notification.removeAllSlots().then(() => { - console.info("==========================>removeAllCallBack=======================>"); + console.info("removeAllSlots sucess"); }); ``` @@ -721,10 +769,14 @@ Subscribes to a notification with the subscription information specified. This A ```js // subscribe callback function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -760,10 +812,14 @@ Subscribes to a notification with the subscription information specified. This A ```js function subscribeCallback(err) { - console.info("==========================>subscribeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -796,13 +852,17 @@ Subscribes to a notification with the subscription information specified. This A ```js function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } } var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("==========================>subscribeCallback=======================>"); + console.info("subscribe sucess"); }); ``` @@ -831,13 +891,17 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu ```js function unsubscribeCallback(err) { - console.info("==========================>unsubscribeCallback=======================>"); + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe success"); + } } -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -865,14 +929,14 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onConsumeCallback(data) { - console.info("==========================>onConsumeCallback=======================>"); +function onCancelCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onConsume: onConsumeCallback + onCancel: onCancelCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("==========================>unsubscribeCallback=======================>"); + console.info("unsubscribe sucess"); }); ``` @@ -902,7 +966,11 @@ Sets whether to enable notification for a specified bundle. This API uses an asy ```js function enableNotificationCallback(err) { - console.info("==========================>enableNotificationCallback=======================>"); + if (err.code) { + console.info("enableNotification failed " + JSON.stringify(err)); + } else { + console.info("enableNotification success"); + } } var bundle = { bundle: "bundleName1", @@ -938,7 +1006,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("==========================>enableNotificationCallback=======================>"); + console.info("enableNotification sucess"); }); ``` @@ -967,7 +1035,11 @@ Checks whether notification is enabled for a specified bundle. This API uses an ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } var bundle = { bundle: "bundleName1", @@ -1008,7 +1080,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1036,7 +1108,11 @@ Checks whether notification is enabled for this application. This API uses an as ```js function isNotificationEnabledCallback(err, data) { - console.info("==========================>isNotificationEnabledCallback=======================>"); + if (err.code) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } } Notification.isNotificationEnabled(isNotificationEnabledCallback); @@ -1072,7 +1148,7 @@ Checks whether notification is enabled for this application. This API uses a pro ```js Notification.isNotificationEnabled().then((data) => { - console.info("==========================>isNotificationEnabledCallback=======================>"); + console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -1102,7 +1178,11 @@ Sets whether to enable the notification badge for a specified bundle. This API u ```js function displayBadgeCallback(err) { - console.info("==========================>displayBadgeCallback=======================>"); + if (err.code) { + console.info("displayBadge failed " + JSON.stringify(err)); + } else { + console.info("displayBadge success"); + } } var bundle = { bundle: "bundleName1", @@ -1138,7 +1218,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("==========================>displayBadgeCallback=======================>"); + console.info("displayBadge sucess"); }); ``` @@ -1167,7 +1247,11 @@ Checks whether the notification badge is enabled for a specified bundle. This AP ```js function isBadgeDisplayedCallback(err, data) { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + if (err.code) { + console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + } else { + console.info("isBadgeDisplayed success"); + } } var bundle = { bundle: "bundleName1", @@ -1208,7 +1292,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("==========================>isBadgeDisplayedCallback=======================>"); + console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); }); ``` @@ -1238,7 +1322,11 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous ```js function setSlotByBundleCallback(err) { - console.info("==========================>setSlotByBundleCallback=======================>"); + if (err.code) { + console.info("setSlotByBundle failed " + JSON.stringify(err)); + } else { + console.info("setSlotByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1280,7 +1368,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("==========================>setSlotByBundleCallback=======================>"); + console.info("setSlotByBundle sucess"); }); ``` @@ -1309,7 +1397,11 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron ```js function getSlotsByBundleCallback(err, data) { - console.info("==========================>getSlotsByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotsByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotsByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1350,7 +1442,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("==========================>getSlotsByBundleCallback=======================>"); + console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1379,7 +1471,11 @@ Obtains the number of notification slots of a specified bundle. This API uses an ```js function getSlotNumByBundleCallback(err, data) { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + if (err.code) { + console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotNumByBundle success"); + } } var bundle = { bundle: "bundleName1", @@ -1420,7 +1516,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("==========================>getSlotNumByBundleCallback=======================>"); + console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1428,7 +1524,7 @@ Notification.getSlotNumByBundle(bundle).then((data) => { ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\): void +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1441,16 +1537,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Parameters** | Name | Type | Mandatory| Description | -| --------------- | ----------------------------------- | ---- | -------------------- | +| --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } var bundle = { bundle: "bundleName1", @@ -1459,14 +1560,15 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey, removeCallback); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason, removeCallback); ``` ## Notification.remove -remove(bundle: BundleOption, notificationKey: NotificationKey): Promise\ +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1482,6 +1584,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -1493,8 +1596,9 @@ var notificationKey = { id: 0, label: "label", } -Notification.remove(bundle, notificationKey).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(bundle, notificationKey, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1502,7 +1606,7 @@ Notification.remove(bundle, notificationKey).then(() => { ## Notification.remove -remove(hashCode: string, callback: AsyncCallback\): void +remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. @@ -1517,6 +1621,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | hashCode | string | Yes | Unique notification ID. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1525,17 +1630,21 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal var hashCode = 'hashCode' function removeCallback(err) { - console.info("==========================>removeCallback=======================>"); + if (err.code) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } } - -Notification.remove(hashCode, removeCallback); +var reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; +Notification.remove(hashCode, reason, removeCallback); ``` ## Notification.remove -remove(hashCode: string): Promise\ +remove(hashCode: string, reason: RemoveReason): Promise\ Removes a notification for a specified bundle. This API uses a promise to return the result. @@ -1550,14 +1659,15 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| +| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | **Example** ```js var hashCode = 'hashCode' - -Notification.remove(hashCode).then(() => { - console.info("==========================>removeCallback=======================>"); +var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +Notification.remove(hashCode, reason).then(() => { + console.info("remove sucess"); }); ``` @@ -1586,7 +1696,11 @@ Removes all notifications for a specified bundle. This API uses an asynchronous ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var bundle = { bundle: "bundleName1", @@ -1618,7 +1732,11 @@ Removes all notifications. This API uses an asynchronous callback to return the ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } Notification.removeAll(removeAllCallback); @@ -1648,7 +1766,7 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js Notification.removeAll().then(() => { - console.info("==========================>removeAllCallback=======================>"); + console.info("removeAll sucess"); }); ``` @@ -1675,7 +1793,11 @@ Removes all notifications for a specified user. This API uses an asynchronous ca ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1705,7 +1827,11 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js function removeAllCallback(err) { - console.info("==========================>removeAllCallback=======================>"); + if (err.code) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } } var userId = 1 @@ -1736,7 +1862,11 @@ Obtains all active notifications. This API uses an asynchronous callback to retu ```js function getAllActiveNotificationsCallback(err, data) { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getAllActiveNotifications success"); + } } Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); @@ -1766,7 +1896,7 @@ Obtains all active notifications. This API uses a promise to return the result. ```js Notification.getAllActiveNotifications().then((data) => { - console.info("==========================>getAllActiveNotificationsCallback=======================>"); + console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); }); ``` @@ -1790,7 +1920,11 @@ Obtains the number of active notifications. This API uses an asynchronous callba ```js function getActiveNotificationCountCallback(err, data) { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + if (err.code) { + console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotificationCount success"); + } } Notification.getActiveNotificationCount(getActiveNotificationCountCallback); @@ -1816,7 +1950,7 @@ Obtains the number of active notifications. This API uses a promise to return th ```js Notification.getActiveNotificationCount().then((data) => { - console.info("==========================>getActiveNotificationCountCallback=======================>"); + console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); }); ``` @@ -1840,7 +1974,11 @@ Obtains active notifications of this application. This API uses an asynchronous ```js function getActiveNotificationsCallback(err, data) { - console.info("==========================>getActiveNotificationsCallback=======================>"); + if (err.code) { + console.info("getActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotifications success"); + } } Notification.getActiveNotifications(getActiveNotificationsCallback); @@ -1866,7 +2004,7 @@ Obtains active notifications of this application. This API uses a promise to ret ```js Notification.getActiveNotifications().then((data) => { - console.info("==========================>getActiveNotificationsCallback=======================>"); + console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -1891,7 +2029,11 @@ Cancels a notification group of this application. This API uses an asynchronous ```js function cancelGroupCallback(err) { - console.info("==========================>cancelGroupCallback=======================>"); + if (err.code) { + console.info("cancelGroup failed " + JSON.stringify(err)); + } else { + console.info("cancelGroup success"); + } } var groupName = "GroupName"; @@ -1920,7 +2062,7 @@ Cancels a notification group of this application. This API uses a promise to ret ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("==========================>cancelGroupPromise=======================>"); + console.info("cancelGroup sucess"); }); ``` @@ -1950,7 +2092,11 @@ Removes a notification group for a specified bundle. This API uses an asynchrono ```js function removeGroupByBundleCallback(err) { - console.info("==========================>removeGroupByBundleCallback=======================>"); + if (err.code) { + console.info("removeGroupByBundle failed " + JSON.stringify(err)); + } else { + console.info("removeGroupByBundle success"); + } } var bundleOption = {bundle: "Bundle"}; @@ -1986,7 +2132,7 @@ Removes a notification group for a specified bundle. This API uses a promise to var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("==========================>removeGroupByBundlePromise=======================>"); + console.info("removeGroupByBundle sucess"); }); ``` @@ -2015,7 +2161,11 @@ Sets the DND time. This API uses an asynchronous callback to return the result. ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2056,7 +2206,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2085,7 +2235,11 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t ```js function setDoNotDisturbDateCallback(err) { - console.info("==========================>setDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } } var doNotDisturbDate = { @@ -2132,7 +2286,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("==========================>setDoNotDisturbDatePromise=======================>"); + console.info("setDoNotDisturbDate sucess"); }); ``` @@ -2159,7 +2313,11 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); @@ -2189,7 +2347,7 @@ Obtains the DND time. This API uses a promise to return the result. ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2217,7 +2375,11 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback ```js function getDoNotDisturbDateCallback(err,data) { - console.info("==========================>getDoNotDisturbDateCallback=======================>"); + if (err.code) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } } var userId = 1 @@ -2257,7 +2419,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("==========================>getDoNotDisturbDatePromise=======================>"); + console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); }); ``` @@ -2284,7 +2446,11 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback ```js function supportDoNotDisturbModeCallback(err,data) { - console.info("==========================>supportDoNotDisturbModeCallback=======================>"); + if (err.code) { + console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + } else { + console.info("supportDoNotDisturbMode success"); + } } Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); @@ -2314,7 +2480,7 @@ Checks whether the DND mode is supported. This API uses a promise to return the ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("==========================>supportDoNotDisturbModePromise=======================>"); + console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); }); ``` @@ -2340,7 +2506,11 @@ Checks whether a specified template exists. This API uses an asynchronous callba ```javascript var templateName = 'process'; function isSupportTemplateCallback(err, data) { - console.info("isSupportTemplateCallback"); + if (err.code) { + console.info("isSupportTemplate failed " + JSON.stringify(err)); + } else { + console.info("isSupportTemplate success"); + } } Notification.isSupportTemplate(templateName, isSupportTemplateCallback); @@ -2374,7 +2544,7 @@ Checks whether a specified template exists. This API uses a promise to return th var templateName = 'process'; Notification.isSupportTemplate(templateName).then((data) => { - console.info("isSupportTemplateCallback"); + console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` @@ -2398,7 +2568,11 @@ Requests notification to be enabled for this application. This API uses an async ```javascript function requestEnableNotificationCallback() { - console.log('------------- requestEnabledNotification --------------'); + if (err.code) { + console.info("requestEnableNotification failed " + JSON.stringify(err)); + } else { + console.info("requestEnableNotification success"); + } }; Notification.requestEnableNotification(requestEnableNotificationCallback); @@ -2419,7 +2593,7 @@ Requests notification to be enabled for this application. This API uses a promis ```javascript Notification.requestEnableNotification() .then(() => { - console.info("requestEnableNotification "); + console.info("requestEnableNotification sucess"); }); ``` @@ -2447,7 +2621,11 @@ Sets whether this device supports distributed notifications. This API uses an as ```javascript function enabledNotificationCallback() { - console.log('----------- enableDistributed ------------'); + if (err.code) { + console.info("enableDistributed failed " + JSON.stringify(err)); + } else { + console.info("enableDistributed success"); + } }; var enable = true @@ -2482,7 +2660,7 @@ var enable = true Notification.enableDistributed(enable) .then(() => { - console.log('-------- enableDistributed ----------'); + console.info("enableDistributed sucess"); }); ``` @@ -2505,7 +2683,11 @@ Obtains whether this device supports distributed notifications. This API uses an ```javascript function isDistributedEnabledCallback() { - console.log('----------- isDistributedEnabled ------------'); + if (err.code) { + console.info("isDistributedEnabled failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabled success"); + } }; Notification.isDistributedEnabled(isDistributedEnabledCallback); @@ -2532,7 +2714,7 @@ Obtains whether this device supports distributed notifications. This API uses a ```javascript Notification.isDistributedEnabled() .then((data) => { - console.log('-------- isDistributedEnabled ----------'); + console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); }); ``` @@ -2561,7 +2743,11 @@ Sets whether an application supports distributed notifications based on the bund ```javascript function enableDistributedByBundleCallback() { - console.log('----------- enableDistributedByBundle ------------'); + if (err.code) { + console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + } else { + console.info("enableDistributedByBundle success"); + } }; var bundle = { @@ -2605,7 +2791,7 @@ var enable = true Notification.enableDistributedByBundle(bundle, enable) .then(() => { - console.log('-------- enableDistributedByBundle ----------'); + console.info("enableDistributedByBundle sucess"); }); ``` @@ -2632,7 +2818,11 @@ Obtains whether an application supports distributed notifications based on the b ```javascript function isDistributedEnabledByBundleCallback(data) { - console.log('----------- isDistributedEnabledByBundle ------------', data); + if (err.code) { + console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabledByBundle success"); + } }; var bundle = { @@ -2677,7 +2867,7 @@ var bundle = { Notification.isDistributedEnabledByBundle(bundle) .then((data) => { - console.log('-------- isDistributedEnabledByBundle ----------', data); + console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); }); ``` @@ -2704,7 +2894,11 @@ Obtains the notification reminder type. This API uses an asynchronous callback t ```javascript function getDeviceRemindTypeCallback(data) { - console.log('----------- getDeviceRemindType ------------', data); + if (err.code) { + console.info("getDeviceRemindType failed " + JSON.stringify(err)); + } else { + console.info("getDeviceRemindType success"); + } }; Notification.getDeviceRemindType(getDeviceRemindTypeCallback); @@ -2735,7 +2929,7 @@ Obtains the notification reminder type. This API uses a promise to return the re ```javascript Notification.getDeviceRemindType() .then((data) => { - console.log('-------- getDeviceRemindType ----------', data); + console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); }); ``` @@ -2766,7 +2960,11 @@ Publishes an agent-powered notification. This API uses an asynchronous callback ```js // Callback for publishAsBundle function publishAsBundleCallback(err) { - console.info("==========================>publishAsBundleCallback=======================>"); + if (err.code) { + console.info("publishAsBundle failed " + JSON.stringify(err)); + } else { + console.info("publishAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2830,7 +3028,7 @@ var notificationRequest = { } Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("==========================>publishAsBundleCallback=======================>"); + console.info("publishAsBundle sucess"); }); ``` @@ -2862,7 +3060,11 @@ Cancels a notification published by the reminder agent. This API uses an asynchr ```js //cancelAsBundle function cancelAsBundleCallback(err) { - console.info("==========================>cancelAsBundleCallback=======================>"); + if (err.code) { + console.info("cancelAsBundle failed " + JSON.stringify(err)); + } else { + console.info("cancelAsBundle success"); + } } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" @@ -2903,7 +3105,7 @@ let representativeBundle = "com.example.demo" let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { - console.info("==========================>cancelAsBundleCallback=======================>"); + console.info("cancelAsBundle success"); }); ``` @@ -2933,7 +3135,11 @@ Sets the enabled status for a notification slot of a specified type. This API us ```js //enableNotificationSlot function enableSlotCallback(err) { - console.log('===================>enableSlotCallback==================>'); + if (err.code) { + console.info("enableNotificationSlot failed " + JSON.stringify(err)); + } else { + console.info("enableNotificationSlot success"); + } }; Notification.enableNotificationSlot( @@ -2971,7 +3177,7 @@ Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION, true).then(() => { - console.log('====================>enableNotificationSlot====================>'); + console.info("enableNotificationSlot sucess"); }); ``` @@ -3000,7 +3206,11 @@ Obtains the enabled status of the notification slot of a specified type. This AP ```js //isNotificationSlotEnabled function getEnableSlotCallback(err, data) { - console.log('===================>getEnableSlotCallback=================='); + if (err.code) { + console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationSlotEnabled success"); + } }; Notification.isNotificationSlotEnabled( @@ -3042,7 +3252,7 @@ Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, Notification.SlotType.SOCIAL_COMMUNICATION ).then((data) => { - console.log('====================>isNotificationSlotEnabled====================>'); + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3074,7 +3284,11 @@ let userId = 100; let enable = true; function setSyncNotificationEnabledWithoutAppCallback(err) { - console.log('setSyncNotificationEnabledWithoutAppCallback'); + if (err.code) { + console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + } else { + console.info("setSyncNotificationEnabledWithoutApp success"); + } } Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); @@ -3113,11 +3327,11 @@ let userId = 100; let enable = true; Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then((data) => { - console.log('setSyncNotificationEnabledWithoutApp'); + .then(() => { + console.info('setSyncNotificationEnabledWithoutApp'); }) .catch((err) => { - console.log('setSyncNotificationEnabledWithoutApp, err:', err); + console.info('setSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3148,9 +3362,9 @@ let userId = 100; function getSyncNotificationEnabledWithoutAppCallback(data, err) { if (err) { - console.log('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); } else { - console.log('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); } } @@ -3189,10 +3403,10 @@ let userId = 100; Notification.getSyncNotificationEnabledWithoutApp(userId) .then((data) => { - console.log('getSyncNotificationEnabledWithoutApp, data:', data); + console.info('getSyncNotificationEnabledWithoutApp, data:', data); }) .catch((err) => { - console.log('getSyncNotificationEnabledWithoutApp, err:', err); + console.info('getSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3236,7 +3450,7 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringify(data1)); + console.info('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { console.error('===> getWant failed because' + JSON.stringify(err)); @@ -3877,3 +4091,14 @@ Notification.subscribe(subscriber, subscribeCallback); | TYPE_NORMAL | 0 | Normal notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | + +## RemoveReason9+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| CLICK_REASON_REMOVE | 1 | The notification is removed due to a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index d133b1b37776187ac1120f42ead17e98273f0db4..b397ba221d3d570e3b5eca2f551ecee228bdfc35 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -37,4 +37,4 @@ export default class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 26d35ffeca4fe9c60ae46d8a8794fe46cb3d1748..ec920f58cab6825ce1dd286f42d1eb24e759f10b 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -384,6 +384,27 @@ promise.then(data => { }); ``` +## radio.isNrSupported7+ + +isNrSupported\(\): boolean + +Checks whether the current device supports 5G \(NR\). + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | - **true**: The current device supports 5G \(NR\).
- **false**: The current device does not support 5G \(NR\).| + +**Example** + +```js +let result = radio.isNrSupported(); +console.log("Result: "+ result); +``` + ## radio.isNrSupported8+ 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-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index ae9a1ece9c9b419ea23162f354d7a428bd104a6c..6622b4b719e95f2c87af19653fbf8a89905239f2 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2683,8 +2683,6 @@ getOpKey(slotId: number): Promise Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2716,8 +2714,6 @@ getOpName(slotId: number, callback: AsyncCallback): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2742,8 +2738,6 @@ getOpName(slotId: number): Promise Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.Telephony.CoreService **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 77dd0bc0560d11837a5cfbb68f38fd3f39075310..cd0995948cc8354d05845c7156abcdfdfb558bda 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -316,7 +316,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { return; } console.log('bind success'); - let promise = udp.getState({}); + let promise = udp.getState(); promise.then(data => { console.log('getState success:' + JSON.stringify(data)); }).catch(err => { @@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. | Name | Type | Mandatory| Description | | ------- | ---------------------------------- | ---- | -------------- | -| data | string | Yes | Data to send. | +| data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| ## UDPExtraOptions @@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| data | string | Yes | Data to send. | +| data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| ## TCPExtraOptions 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/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index daa6d4aac0d3ea39560a13de07b37c51c8b9226a..0a46cec929810e8f485a66b26445f1e3042b7672 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,6 +1,7 @@ # Notification -> ![icon-note.gif]public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -51,18 +52,17 @@ Displays a notification. **Example** ```javascript -export default { - show() { - notification.show({ - contentTitle: 'title info', - contentText: 'text', - clickAction: { - bundleName: 'com.example.testapp', - abilityName: 'notificationDemo', - uri: '/path/to/notification', - }, - }); - }, +export default { + show() { + notification.show({ + contentTitle: 'title info', + contentText: 'text', + clickAction: { + bundleName: 'com.example.testapp', + abilityName: 'notificationDemo', + uri: '/path/to/notification', + }, + }); + }, } -; ``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 7d8018a4e82916df0c218a10ca7d5e8fdb9e6364..f3a29a9cc683fecc38b4c935af7607bd2a5415b8 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -63,6 +63,29 @@ promise.then((data) => { }); ``` +## data.getDefaultCellularDataSlotIdSync + +getDefaultCellularDataSlotIdSync(): number + +Obtains the default SIM card used for mobile data synchronously. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| ------ | -------------------------------------------------- | +| number | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Example** + +```js +console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) +``` + + ## data.setDefaultCellularDataSlotId setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 91013f97245cf0b63073b88c51af91705324038a..bcbac5414055dfb654ab1264ab04f92e629cb3f3 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -43,13 +43,13 @@ Obtains an **OnlineUpdater** object. ```ts try { - var upgradeInfo = { + const upgradeInfo = { upgradeApp: "com.ohos.ota.updateclient", businessType: { vendor: update.BusinessVendor.PUBLIC, subType: update.BusinessSubType.FIRMWARE } - } + }; let updater = update.getOnlineUpdater(upgradeInfo); } catch(error) { console.error(`Fail to get updater error: ${error}`); @@ -233,15 +233,15 @@ Obtains the description file of the new version. This API uses an asynchronous c ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); @@ -276,15 +276,15 @@ Obtains the description file of the new version. This API uses a promise to retu ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); @@ -368,10 +368,10 @@ Obtains the description file of the current version. This API uses an asynchrono ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); @@ -405,10 +405,10 @@ Obtains the description file of the current version. This API uses a promise to ```ts // Options of the description file -var descriptionOptions = { +const descriptionOptions = { format: update.DescriptionFormat.STANDARD, // Standard format language: "zh-cn" // Chinese -} +}; updater.getCurrentVersionDescription(descriptionOptions).then(info => { console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); @@ -489,15 +489,15 @@ Downloads the new version. This API uses an asynchronous callback to return the ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions, (err) => { console.log(`download error ${JSON.stringify(err)}`); }); @@ -530,15 +530,15 @@ Downloads the new version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Download options -var downloadOptions = { +const downloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network order: update.Order.DOWNLOAD // Download -} +}; updater.download(versionDigestInfo, downloadOptions).then(() => { console.log(`download start`); }).catch(err => { @@ -568,14 +568,14 @@ Resumes download of the new version. This API uses an asynchronous callback to r ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { console.log(`resumeDownload error ${JSON.stringify(err)}`); }); @@ -608,14 +608,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for resuming download -var resumeDownloadOptions = { +const resumeDownloadOptions = { allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network -} +}; updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { console.log(`resumeDownload start`); }).catch(err => { @@ -645,14 +645,14 @@ Pauses download of the new version. This API uses an asynchronous callback to re ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { console.log(`pauseDownload error ${JSON.stringify(err)}`); }); @@ -685,14 +685,14 @@ Resumes download of the new version. This API uses a promise to return the resul ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for pausing download -var pauseDownloadOptions = { +const pauseDownloadOptions = { isAllowAutoResume: true // Whether to allow automatic resuming of download -} +}; updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { console.log(`pauseDownload`); }).catch(err => { @@ -722,14 +722,14 @@ Updates the version. This API uses an asynchronous callback to return the result ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { console.log(`upgrade error ${JSON.stringify(err)}`); }); @@ -762,14 +762,14 @@ Updates the version. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Installation options -var upgradeOptions = { +const upgradeOptions = { order: update.Order.INSTALL // Installation command -} +}; updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { console.log(`upgrade start`); }).catch(err => { @@ -799,14 +799,14 @@ Clears errors. This API uses an asynchronous callback to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +const clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions, (err) => { console.log(`clearError error ${JSON.stringify(err)}`); }); @@ -839,14 +839,14 @@ Clears errors. This API uses a promise to return the result. ```ts // Version digest information -var versionDigestInfo = { +const versionDigestInfo = { versionDigest: "versionDigest" // Version digest information in the check result -} +}; // Options for clearing errors -var clearOptions = { +lconstet clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, -} +}; updater.clearError(versionDigestInfo, clearOptions).then(() => { console.log(`clearError success`); }).catch(err => { @@ -926,7 +926,7 @@ Sets the update policy. This API uses an asynchronous callback to return the res **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -961,7 +961,7 @@ Sets the update policy. This API uses a promise to return the result. **Example** ```ts -let policy = { +const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes @@ -1041,10 +1041,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.on(eventClassifyInfo, (eventInfo) => { console.log("updater on " + JSON.stringify(eventInfo)); @@ -1068,10 +1068,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; updater.off(eventClassifyInfo, (eventInfo) => { console.log("updater off " + JSON.stringify(eventInfo)); @@ -1153,10 +1153,10 @@ Verifies the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { console.log(`factoryReset error ${JSON.stringify(err)}`); @@ -1189,10 +1189,10 @@ Verifies the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFile = { +const upgradeFile = { fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -} +}; localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { console.log(`verifyUpgradePackage success`); }).catch(err => { @@ -1219,10 +1219,10 @@ Installs the update package. This API uses an asynchronous callback to return th **Example** ```ts -var upgradeFiles = [{ +const upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles, (err) => { console.log(`applyNewVersion error ${JSON.stringify(err)}`); @@ -1248,10 +1248,10 @@ Installs the update package. This API uses a promise to return the result. **Example** ```ts -var upgradeFiles = [{ +localUpdater upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package -}] +}]; localUpdater.applyNewVersion(upgradeFiles).then(() => { console.log(`applyNewVersion success`); }).catch(err => { @@ -1276,10 +1276,10 @@ Enables listening for update events. This API uses an asynchronous callback to r **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); @@ -1305,10 +1305,10 @@ Disables listening for update events. This API uses an asynchronous callback to **Example** ```ts -var eventClassifyInfo = { +const eventClassifyInfo = { eventClassify: update.EventClassify.TASK, // Listening for update events extraInfo: "" -} +}; function onTaskUpdate(eventInfo) { console.log(`on eventInfo id `, eventInfo.eventId); diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 699ab299f5050594fd943c95e36c0538e9d0ec24..95654a5829967c3e6f3be2be8c5daf3baf527386 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -31,6 +31,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | | callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js @@ -76,6 +84,14 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | ------------------- | -------------------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). + +| ID| Error Message | +| -------- | ------------------------- | +| 14600101 | Device operation failed.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 52f5367110bc35c33075ed291a796a657a468816..bda4ad227b32b18130682bb4fe10db9a446535ec 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -433,7 +433,7 @@ ws.off('open', callback1); on\(type: 'message', callback: AsyncCallback\): void -Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). @@ -462,7 +462,7 @@ ws.on('message', (err, value) => { off\(type: 'message', callback?: AsyncCallback\): void -Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. +Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented. >![](public_sys-resources/icon-note.gif) **NOTE:** >The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\). diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 13014cfed8a6cc95d124535c89b399b12348395f..a8221a78898accf8d18724193df311a13693b998 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -302,7 +302,7 @@ Represents the WLAN configuration. ## IpType7+ -Enumerate the IP address types. +Enumerates the IP address types. **System API**: This is a system API. @@ -1851,7 +1851,7 @@ Unregisters the WLAN state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -1909,7 +1909,7 @@ Unregisters the WLAN connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -1952,7 +1952,7 @@ Unregisters the WLAN scan state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiRssiChange')7+ @@ -1988,7 +1988,7 @@ Unregisters the RSSI change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -2033,7 +2033,7 @@ Unregisters the hotspot state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -2078,7 +2078,7 @@ Unregisters the P2P state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -2114,7 +2114,7 @@ Unregisters the P2P connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -2150,7 +2150,7 @@ Unregisters the P2P device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -2186,7 +2186,7 @@ Unregisters the P2P peer device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| -| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -2222,7 +2222,7 @@ Unregisters the P2P persistent group state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ @@ -2265,4 +2265,4 @@ Unregisters the P2P device discovery state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| 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-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1bc12e9014024c9c3fe02f783ca6d65934f98d9f..156e4ca3ac3c5b6e821258ce8baf77cd4f51322c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -55,7 +55,7 @@ Creates a time picker whose default time range is from 00:00 to 23:59. @Entry @Component struct TimePickerExample { - private selectedTime: Date = new Date('7/22/2022 8:00:00') + private selectedTime: Date = new Date('2022-07-22T08:00:00') build() { Column() { 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-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-attributes-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index c02876ce0f77ca67db58378aa68dc044846dbc75..c82ec4fab433b607cf344864a1126ac94332e89c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -78,4 +78,4 @@ struct ImageEffectsExample { } ``` -image-effect +![](figures/image-effect.png) 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/reference/errorcodes/errorcode-huks.md b/en/application-dev/reference/errorcodes/errorcode-huks.md new file mode 100644 index 0000000000000000000000000000000000000000..7bab2f0be7353cefecbe458b6435aaaf213429d4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-huks.md @@ -0,0 +1,228 @@ +# HUKS Error Codes + +## 12000001 Feature Not Supported + +**Error Message** + +`${messageInfo}` is not supported. + +**Possible Causes** + +The API is supported, but certain features in the API, such as the algorithm, are not supported. + +**Procedure** + +Modify the parameters and use the features supported. + +## 12000002 Missing Key Algorithm Parameter +**Error Message** + +Failed to obtain `${messageInfo}`. It is not set in ParamSet. + +**Possible Causes** + +The key parameter is not set. + +**Procedure** + +1. Determine the missing parameter from the error message. +2. Set the parameter. + +## 12000003 Invalid Key Algorithm Parameter + +**Error Message** + +Invalid `${messageInfo}`. + +**Possible Causes** + +An invalid parameter is found. + +**Procedure** + +1. Determine the invalid parameter from the error message. +2. Correct the invalid parameter. + +## 12000004 File Error + +**Error Message** + +Failed to read the file. + +Failed to write the file. + +**Possible Causes** + +The file operation failed. + +**Procedure** + +1. Check whether the disk space is used up and whether the file system is abnormal. +2. Clear the disk space. + +## 12000005 IPC Error + +**Error Message** + +IPC timed out. + +Failed to obtain messages from IPC. + +**Possible Causes** + +IPC failed. + +**Procedure** + +Locate and rectify the IPC failure. + +## 12000006 Algorithm Library Operation Failed + +**Error Message** + +Crypto engine error. + +**Possible Causes** + +The algorithm library operation fails. The possible causes include the following: + +1. The encryption and decryption on the algorithm library failed due to incorrect ciphertext data. +2. Incorrect key parameters exist. + +**Procedure** + +1. Check and correct the ciphertext data. +2. Check and correct the key parameters. + +## 12000007 Failed to Access the Key Due to Invalidated Credential + +**Error Message** + +This credential is invalidated permanently. + +**Possible Causes** + +The possible causes include the following: + +1. The key is configured with the user access control attribute and becomes invalid after the password is cleared. +2. The key is configured with the user access control attribute and becomes invalid after a new biometric feature is enrolled. + +**Procedure** + +1. Locate the cause of the authentication failure based on the log. +2. If the authentication fails due to the access control attribute configured, the key cannot be used any more. + +## 12000008 Failed to Access the Key Due to a Failure in Authentication Token Verification + +**Error Message** + +The authentication token verification failed. + +**Possible Causes** + +The authentication token verification failed due to an incorrect challenge value. + +**Procedure** + +1. Check whether the challenge for userIAM authentication is correctly assembled. +2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication. + +## 12000009 Key Access Timed Out + +**Error Message** + +The Authentication token timed out. + +**Possible Causes** + +The authentication failed because the authentication token timed out. + +**Procedure** + +The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected. + +## 12000010 Key Operation Sessions Reaches the Limit + +**Error Message** + +The number of key operation sessions has reached the limit. + +**Possible Causes** + +The number of concurrent key operation sessions has reached the maximum (15). + +**Procedure** + +1. Check whether there are multiple key session operations (**init** operations) for the same application. If yes, modify the code to avoid concurrent invoking. +2. If the key operation sessions are set up for different applications, wait until the sessions are released. + +## 12000011 The Entity Does Not Exist + +**Error Message** + +The entity does not exist. + +**Possible Causes** + +The key corresponding to the key alias does not exist. + +**Procedure** + +1. Check whether the key alias is misspelled. +2. Check whether the key corresponding to the key alias is successfully generated. + +## 12000012 External Error + +**Error Message** + +External error `${messageInfo}`. + +**Possible Causes** + +An external error, such as a hardware fault or file error occurs. + +**Procedure** + +Provide the error code and log information to the related party. + +## 12000013 The Credential Does Not Exist + +**Error Message** + +The credential does not exist. + +**Possible Causes** + +The credential, such as the PIN, fingerprint, or face image, is not enrolled. + +**Procedure** + +Enroll the credential or change the authentication type bound to the key. + +## 12000014 Insufficient Memory + +**Error Message** + +Memory is insufficient. + +**Possible Causes** + +The system memory is insufficient. + +**Procedure** + +Release memory or restart the device. + +## 12000015 Failed to Invoke Other System Services + +**Error Message** + +Failed to call the `${messageInfo}` service to do `${messageInfo}`. + +**Possible Causes** + +The called system service has not started. + +**Procedure** + +Wait for the system service to start and call the API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensor.md b/en/application-dev/reference/errorcodes/errorcode-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..571156ec00328b0ba564cd6174e6fb81aa5154b1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-sensor.md @@ -0,0 +1,20 @@ +# Sensor Error Codes + +## 14500101 Service exception. + +**Error Message** + +Service exception. + +**Description** + +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. + +**Possible Causes** + +The HDI service is abnormal. + +**Procedure** + +1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. +2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. diff --git a/en/application-dev/reference/errorcodes/errorcode-vibrator.md b/en/application-dev/reference/errorcodes/errorcode-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..f5dc329c1e96d945f76c7625b365a53fe50477b4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -0,0 +1,21 @@ +# Vibrator Error Codes + +## 14600101 Device operation failed. + +**Error Message** + +Device operation failed. + +**Description** + +This error code is reported if the HDI service is abnormal or the device is occupied when the **startVibration** interface of the vibrator module is called. + +**Possible Causes** + +1. The HDI service is abnormal. +2. The device is occupied. + +**Procedure** + +1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. +2. Set a higher priority for the vibrator. 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%') + } +} +``` ## 相关实例 基于后台代理提醒开发,有以下相关实例可供参考: -- [`AlarmClock`:后台代理提醒(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) +- [`AlarmClock`:后台代理提醒(ArkTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) -- [`FlipClock`:翻页时钟(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/CompleteApps/FlipClock) +- [`FlipClock`:翻页时钟(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/CompleteApps/FlipClock) -- [闹钟应用(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file +- [闹钟应用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file 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 b279133c7705c8940cddf4721847b00b50156daa..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,95 +402,8 @@ 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(); -``` - ## 相关实例 基于后台任务管理,有以下相关实例可供参考: -- [`BackgroundTaskManager`:后台任务管理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file +- [`BackgroundTaskManager`:后台任务管理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file 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 300086d76e88216b98d0e7f67b0a112ec95b7913..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,141 +61,114 @@ 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); + }); +``` ## 相关实例 基于延迟任务调度,有以下相关实例可供参考: -- [`WorkScheduler`:延迟任务调度(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/WorkScheduler) \ No newline at end of file +- [`WorkScheduler`:延迟任务调度(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/WorkScheduler) \ No newline at end of file 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/telephony/cellular-network-signal-info.md b/zh-cn/application-dev/telephony/cellular-network-signal-info.md index 8c308e38578da07e19b7fe129fa0af7f47db0ca4..2e37ff8134208b978720953229ee445d8cd922e6 100644 --- a/zh-cn/application-dev/telephony/cellular-network-signal-info.md +++ b/zh-cn/application-dev/telephony/cellular-network-signal-info.md @@ -53,4 +53,4 @@ radio模块提供了获取当前网络信号信息的方法。observer模块为 ## 相关实例 针对蜂窝网络数据开发,有以下相关实例可供参考: -- [`MobileNetwork`:蜂窝数据(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/MobileNetwork) \ No newline at end of file +- [`MobileNetwork`:蜂窝数据(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/MobileNetwork) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index 8131710e12f0374526d018ad93b998b7aff41f45..ed72f79bff42a7a00559edc1703d06311809c50e 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -3,37 +3,30 @@ - [方舟开发框架(ArkUI)概述](arkui-overview.md) - UI开发(基于ArkTS的声明式开发范式) - [概述](ui-ts-overview.md) - - 框架说明 - - 文件组织 - - [目录结构](ts-framework-directory.md) - - [应用代码文件访问规则](ts-framework-file-access-rules.md) - - 资源管理 - - [资源文件的分类](ui-ts-basic-resource-file-categories.md) - - [资源访问](ts-resource-access.md) - - [像素单位](ts-pixel-units.md) - - - 深入理解组件化 - - [自定义组件初始化](ts-custom-component-initialization.md) - - [自定义组件生命周期回调函数](ts-custom-component-lifecycle-callbacks.md) - - [组件创建和重新初始化示例](ts-component-creation-re-initialization.md) - - 常见组件开发指导 - - [Button开发指导](ui-ts-basic-components-button.md) - - [Web开发指导](ui-ts-components-web.md) - - 常见布局开发指导 - - [弹性布局](ui-ts-layout-flex.md) - - [栅格布局](ui-ts-layout-grid-container.md) - - [媒体查询](ui-ts-layout-mediaquery.md) - - 体验声明式UI - - [创建声明式UI工程](ui-ts-creating-project.md) - - [初识Component](ui-ts-components.md) - - [创建简单视图](ui-ts-creating-simple-page.md) - - 页面布局与连接 + - [声明式UI开发指导](ui-ts-developing-intro.md) + - 声明式开发实例 + - [创建简单视图](ui-ts-creating-simple-page.md) + - 构建完整实例 - [构建食物数据模型](ui-ts-building-data-model.md) - [构建食物列表List布局](ui-ts-building-category-list-layout.md) - [构建食物分类Grid布局](ui-ts-building-category-grid-layout.md) - - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) - - [性能提升的推荐方法](ts-performance-improvement-recommendation.md) - + - [页面跳转与数据传递](ui-ts-page-redirection-data-transmission.md) + - 添加闪屏动画 + - [绘制图像](ui-ts-drawing-feature.md) + - [添加动画效果](ui-ts-animation-feature.md) + - 常见布局开发指导 + - 自适应布局 + - [线性布局](ui-ts-layout-linear.md) + - [层叠布局](ui-ts-layout-stack.md) + - [弹性布局](ui-ts-layout-flex.md) + - [网格布局](ui-ts-layout-grid.md) + - 响应式布局 + - [栅格布局](ui-ts-layout-grid-container.md) + - [栅格布局(新)](ui-ts-layout-grid-container-new.md) + - [媒体查询](ui-ts-layout-mediaquery.md) + - [自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md) + - [Web组件开发指导](ui-ts-components-web.md) + - [性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md) - UI开发(兼容JS的类Web开发范式) - [概述](ui-js-overview.md) - 框架说明 diff --git a/zh-cn/application-dev/ui/arkui-overview.md b/zh-cn/application-dev/ui/arkui-overview.md index fa6a13c44764b405d9233895a71216803086f671..842f41437ad61473148e93a21923e70e045c1052 100644 --- a/zh-cn/application-dev/ui/arkui-overview.md +++ b/zh-cn/application-dev/ui/arkui-overview.md @@ -26,7 +26,7 @@ | 开发范式名称 | 简介 | 适用场景 | 适用人群 | | -------- | ---------------------------------------- | ---------------- | ------------------- | - | 声明式开发范式 | 采用基于TypeScript进行声明式UI语法扩展而来的[ArkTS语言](../quick-start/ets-get-started.md),从组件、动画和状态管理三个维度提供了UI绘制能力。声明式开发范式更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。 | 复杂度较大、团队合作度较高的应用 | 移动系统应用开发人员、系统应用开发人员 | + | 声明式开发范式 | 采用基于TypeScript进行声明式UI语法扩展而来的[ArkTS语言](../quick-start/arkts-get-started.md),从组件、动画和状态管理三个维度提供了UI绘制能力。声明式开发范式更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。 | 复杂度较大、团队合作度较高的应用 | 移动系统应用开发人员、系统应用开发人员 | | 类Web开发范式 | 采用经典的HML、CSS、JavaScript三段式开发方式,使用HML标签文件进行布局搭建,使用CSS文件进行样式描述,使用JavaScript文件进行逻辑处理。UI组件与数据之间通过单向数据绑定的方式建立关联,当数据发生变化时,UI界面自动触发刷新。该开发方式更接近Web前端开发者的使用习惯,便于快速将已有的Web应用改造成方舟开发框架应用。 | 界面较简单的中小型应用和卡片 | Web前端开发人员 | ## 框架结构 diff --git a/zh-cn/application-dev/ui/figures/LazyForEach1.gif b/zh-cn/application-dev/ui/figures/LazyForEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..66730a7cdb85529ed96a084b9d9b98aaed18474d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/LazyForEach1.gif differ diff --git a/zh-cn/application-dev/ui/figures/aboutToAppear.gif b/zh-cn/application-dev/ui/figures/aboutToAppear.gif new file mode 100644 index 0000000000000000000000000000000000000000..6bddc173b59f69a746592ae8689b0443b704a8b3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/aboutToAppear.gif differ diff --git a/zh-cn/application-dev/ui/figures/alignself.png b/zh-cn/application-dev/ui/figures/alignself.png new file mode 100644 index 0000000000000000000000000000000000000000..6ab6ba66e53bf7dc3edd72d44727fe40c7ff0fb9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/alignself.png differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature.gif b/zh-cn/application-dev/ui/figures/animation-feature.gif new file mode 100644 index 0000000000000000000000000000000000000000..f75ac924799af38dbfe43c2c2e5572fb0e3c09d0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature.gif differ diff --git a/zh-cn/application-dev/ui/figures/animation-feature1.gif b/zh-cn/application-dev/ui/figures/animation-feature1.gif new file mode 100644 index 0000000000000000000000000000000000000000..5dc236ba194e59fd46416ca0a738ed7139a59374 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/animation-feature1.gif differ diff --git a/zh-cn/application-dev/ui/figures/blank.gif b/zh-cn/application-dev/ui/figures/blank.gif new file mode 100644 index 0000000000000000000000000000000000000000..879f53781ff9f9087d3343cd867be8d56deeca1e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/blank.gif differ diff --git a/zh-cn/application-dev/ui/figures/breakpoints.gif b/zh-cn/application-dev/ui/figures/breakpoints.gif new file mode 100644 index 0000000000000000000000000000000000000000..f2e18ecafe8202705a34e6c76b4fdc59d5cca8d6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/breakpoints.gif differ diff --git a/zh-cn/application-dev/ui/figures/column.png b/zh-cn/application-dev/ui/figures/column.png new file mode 100644 index 0000000000000000000000000000000000000000..27321b5a24798d6d423cbf76eab974f4ebc2d0fb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/column.png differ diff --git a/zh-cn/application-dev/ui/figures/columnGap.png b/zh-cn/application-dev/ui/figures/columnGap.png new file mode 100644 index 0000000000000000000000000000000000000000..1b7017a280158e88baabca3dfd1e77c6068c4655 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnGap.png differ diff --git a/zh-cn/application-dev/ui/figures/columnTemplate.png b/zh-cn/application-dev/ui/figures/columnTemplate.png new file mode 100644 index 0000000000000000000000000000000000000000..730abeccaffa22f88e916fb199cbc1e44a982789 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnTemplate.png differ diff --git a/zh-cn/application-dev/ui/figures/columnalign.png b/zh-cn/application-dev/ui/figures/columnalign.png new file mode 100644 index 0000000000000000000000000000000000000000..a73a28a23c3719aee5379e0c8b3f9cc3627ca3e2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnalign.png differ diff --git a/zh-cn/application-dev/ui/figures/columnjustify.png b/zh-cn/application-dev/ui/figures/columnjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..34e68343a8b621f4a0567ea9424169f6a7e5ef1b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/columns1.png b/zh-cn/application-dev/ui/figures/columns1.png new file mode 100644 index 0000000000000000000000000000000000000000..f7e2c38a9b5f22ebf44eaae8eb9fea461d198018 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns1.png differ diff --git a/zh-cn/application-dev/ui/figures/columns2.png b/zh-cn/application-dev/ui/figures/columns2.png new file mode 100644 index 0000000000000000000000000000000000000000..5e549b42338ffe87b944807cec7e57144b5cbe74 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns2.png differ diff --git a/zh-cn/application-dev/ui/figures/columns3.gif b/zh-cn/application-dev/ui/figures/columns3.gif new file mode 100644 index 0000000000000000000000000000000000000000..e44df1b36066095ed6e8741e26d9f04a4c9a2b0b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columns3.gif differ diff --git a/zh-cn/application-dev/ui/figures/columnspace.png b/zh-cn/application-dev/ui/figures/columnspace.png new file mode 100644 index 0000000000000000000000000000000000000000..6af047e34c3e1e2ecd8d3d1d99af17ca01c5b58b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/columnspace.png differ diff --git a/zh-cn/application-dev/ui/figures/component.PNG b/zh-cn/application-dev/ui/figures/component.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bf949004e64004c9ac3f24f6edbd625b135c9717 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.PNG differ diff --git a/zh-cn/application-dev/ui/figures/component.gif b/zh-cn/application-dev/ui/figures/component.gif new file mode 100644 index 0000000000000000000000000000000000000000..e50a590ed7049a3c52149d10886e5b38ffdae2a5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/component.gif differ diff --git a/zh-cn/application-dev/ui/figures/crossCenter.png b/zh-cn/application-dev/ui/figures/crossCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..5efa144a653649d5118edf3790c8e26b370c49df Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/crossEnd.png b/zh-cn/application-dev/ui/figures/crossEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..2330225d2b046b67c30c040a4a72e2e553e0c824 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacearound.png b/zh-cn/application-dev/ui/figures/crossSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..280987579ef8c11a847d6842e9596168aec97cdb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpacebetween.png b/zh-cn/application-dev/ui/figures/crossSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..65e408eb2fde074f1a9e65dfff01de8e569ccf66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/crossSpaceevenly.png b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..83f3a801a8f79d06794680db0309a9fa5fee1387 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/crossStart.png b/zh-cn/application-dev/ui/figures/crossStart.png new file mode 100644 index 0000000000000000000000000000000000000000..1f323600a999f2ca313a5a5273088620f72578c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/crossStart.png differ diff --git a/zh-cn/application-dev/ui/figures/direction.png b/zh-cn/application-dev/ui/figures/direction.png new file mode 100644 index 0000000000000000000000000000000000000000..702c9b07fa00b8685415bb83879ead774001ee56 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction.png differ diff --git a/zh-cn/application-dev/ui/figures/direction1.png b/zh-cn/application-dev/ui/figures/direction1.png new file mode 100644 index 0000000000000000000000000000000000000000..1153aade7a6764fe871d63783abdcd09366fba13 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction1.png differ diff --git a/zh-cn/application-dev/ui/figures/direction2.png b/zh-cn/application-dev/ui/figures/direction2.png new file mode 100644 index 0000000000000000000000000000000000000000..e0a74253389934179d0cbcbaf4a43c01df18f7e5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/direction2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature.png b/zh-cn/application-dev/ui/figures/drawing-feature.png new file mode 100644 index 0000000000000000000000000000000000000000..c1468667bdf74b80629c1eaa32cbef935ea5048c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature1.png b/zh-cn/application-dev/ui/figures/drawing-feature1.png new file mode 100644 index 0000000000000000000000000000000000000000..6b3ca4fa90e25b5906bdadcdcbf134bd00b7b34b Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature1.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature2.png b/zh-cn/application-dev/ui/figures/drawing-feature2.png new file mode 100644 index 0000000000000000000000000000000000000000..42fc7cdf9436680a30413c5bb07e02fd3230ec0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature2.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature3.png b/zh-cn/application-dev/ui/figures/drawing-feature3.png new file mode 100644 index 0000000000000000000000000000000000000000..c090ff948d7333f3dea17dd7ec54488638788c0c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature3.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature4.png b/zh-cn/application-dev/ui/figures/drawing-feature4.png new file mode 100644 index 0000000000000000000000000000000000000000..bcfee4728b4d5fc9bfc57e6bb743e708ad0b2379 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature4.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature5.png b/zh-cn/application-dev/ui/figures/drawing-feature5.png new file mode 100644 index 0000000000000000000000000000000000000000..e70c63ed2f601cf4cd30f319dc6ebd74f216c909 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature5.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature6.png b/zh-cn/application-dev/ui/figures/drawing-feature6.png new file mode 100644 index 0000000000000000000000000000000000000000..772bd122cd1ecb252625f59af5ea3e5ff61689fc Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature6.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature7.png b/zh-cn/application-dev/ui/figures/drawing-feature7.png new file mode 100644 index 0000000000000000000000000000000000000000..c77366f46008f173bc117f95bed6bc7827af11cd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature7.png differ diff --git a/zh-cn/application-dev/ui/figures/drawing-feature8.png b/zh-cn/application-dev/ui/figures/drawing-feature8.png new file mode 100644 index 0000000000000000000000000000000000000000..17cdf2ba3b6e3eeabbe93ed3115c34801634ba8e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/drawing-feature8.png differ diff --git a/zh-cn/application-dev/ui/figures/flex.png b/zh-cn/application-dev/ui/figures/flex.png new file mode 100644 index 0000000000000000000000000000000000000000..848ceef3873ed6f83466d9ab42f6aa68cb341fe9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex.png differ diff --git a/zh-cn/application-dev/ui/figures/flex1.PNG b/zh-cn/application-dev/ui/figures/flex1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..cb125f009c7473782b463689466708d49ae474e0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flex1.PNG differ diff --git a/zh-cn/application-dev/ui/figures/flexExample.png b/zh-cn/application-dev/ui/figures/flexExample.png new file mode 100644 index 0000000000000000000000000000000000000000..73d4e3407dad6422e640dc8a27a4347c2c73dd9d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexExample.png differ diff --git a/zh-cn/application-dev/ui/figures/flexbasis.png b/zh-cn/application-dev/ui/figures/flexbasis.png new file mode 100644 index 0000000000000000000000000000000000000000..df26a3272410052e3df94b2c4207015d5d23b613 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexbasis.png differ diff --git a/zh-cn/application-dev/ui/figures/flexgrow.png b/zh-cn/application-dev/ui/figures/flexgrow.png new file mode 100644 index 0000000000000000000000000000000000000000..9c2b84e0e070e67613504dcb52ea02acb6ed72b9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexgrow.png differ diff --git a/zh-cn/application-dev/ui/figures/flexshrink.png b/zh-cn/application-dev/ui/figures/flexshrink.png new file mode 100644 index 0000000000000000000000000000000000000000..20ddfe6941c5313b1054f1d479da8b24014c3928 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/flexshrink.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp1.png b/zh-cn/application-dev/ui/figures/gridExp1.png new file mode 100644 index 0000000000000000000000000000000000000000..6767d92cee335418b9c82aa842359dfce1d887c9 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp1.png differ diff --git a/zh-cn/application-dev/ui/figures/gridExp2.png b/zh-cn/application-dev/ui/figures/gridExp2.png new file mode 100644 index 0000000000000000000000000000000000000000..c484c27c079f3490b32d7e6c2c8e3f0b84a0151a Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridExp2.png differ diff --git a/zh-cn/application-dev/ui/figures/griditem.png b/zh-cn/application-dev/ui/figures/griditem.png new file mode 100644 index 0000000000000000000000000000000000000000..9560e2291add8a9117be6a5ccb90033b960190d5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/griditem.png differ diff --git a/zh-cn/application-dev/ui/figures/gridlayout.png b/zh-cn/application-dev/ui/figures/gridlayout.png new file mode 100644 index 0000000000000000000000000000000000000000..cc0db8ce530d60191adf8ffaefdbf11b97305067 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gridlayout.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter1.png b/zh-cn/application-dev/ui/figures/gutter1.png new file mode 100644 index 0000000000000000000000000000000000000000..3b246c32f1079b06c18c1a14cbcb286c241a8623 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter1.png differ diff --git a/zh-cn/application-dev/ui/figures/gutter2.png b/zh-cn/application-dev/ui/figures/gutter2.png new file mode 100644 index 0000000000000000000000000000000000000000..534c169420509639cf21b30b41d65ccb34758b66 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/gutter2.png differ diff --git a/zh-cn/application-dev/ui/figures/isVisible.gif b/zh-cn/application-dev/ui/figures/isVisible.gif new file mode 100644 index 0000000000000000000000000000000000000000..bdb7b5ae5fe49adfaf4eb48c1533e4fe599be612 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/isVisible.gif differ diff --git a/zh-cn/application-dev/ui/figures/justifyContent.png b/zh-cn/application-dev/ui/figures/justifyContent.png new file mode 100644 index 0000000000000000000000000000000000000000..2e997f9cba6ce5c2ad93c1f2e33728b7db17bdd3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/justifyContent.png differ diff --git a/zh-cn/application-dev/ui/figures/layoutWeight.gif b/zh-cn/application-dev/ui/figures/layoutWeight.gif new file mode 100644 index 0000000000000000000000000000000000000000..b7d0cdeeb268f96427c67daeb1673c5ec1b55ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/layoutWeight.gif differ diff --git a/zh-cn/application-dev/ui/figures/lifecycle.PNG b/zh-cn/application-dev/ui/figures/lifecycle.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a9b5769ad867f880dbe2b746b15de80cadbf799e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/lifecycle.PNG differ diff --git a/zh-cn/application-dev/ui/figures/list1.gif b/zh-cn/application-dev/ui/figures/list1.gif new file mode 100644 index 0000000000000000000000000000000000000000..f421df651539da975e30d2294598e587e44d665e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list1.gif differ diff --git a/zh-cn/application-dev/ui/figures/list2.gif b/zh-cn/application-dev/ui/figures/list2.gif new file mode 100644 index 0000000000000000000000000000000000000000..97d8e42b844537f19ec1fab10aca7af58a45c0a4 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/list2.gif differ diff --git a/zh-cn/application-dev/ui/figures/listcolumn.gif b/zh-cn/application-dev/ui/figures/listcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..4c0d4453b6e8d1207452e65d47c4867d77206115 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/listrow.gif b/zh-cn/application-dev/ui/figures/listrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..16b77e79d3288a84b47feb7b99beac0392a2e4f5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/listrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/mainCenter.png b/zh-cn/application-dev/ui/figures/mainCenter.png new file mode 100644 index 0000000000000000000000000000000000000000..30aa156d5ab296c25e30958cbd3f83ac35de88d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainCenter.png differ diff --git a/zh-cn/application-dev/ui/figures/mainEnd.png b/zh-cn/application-dev/ui/figures/mainEnd.png new file mode 100644 index 0000000000000000000000000000000000000000..fea2431892d09a06f067b438ae9462a09ad97ed0 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainEnd.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacearound.png b/zh-cn/application-dev/ui/figures/mainSpacearound.png new file mode 100644 index 0000000000000000000000000000000000000000..0398af5f8f1a4dece7057ec3b1a852e1518933ef Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacearound.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpacebetween.png b/zh-cn/application-dev/ui/figures/mainSpacebetween.png new file mode 100644 index 0000000000000000000000000000000000000000..d230aa1e735c0964581d1cf17d18af5152a5b466 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpacebetween.png differ diff --git a/zh-cn/application-dev/ui/figures/mainSpaceevenly.png b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png new file mode 100644 index 0000000000000000000000000000000000000000..d22917514351643139709069af9f78419be7c748 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainSpaceevenly.png differ diff --git a/zh-cn/application-dev/ui/figures/mainStart.png b/zh-cn/application-dev/ui/figures/mainStart.png new file mode 100644 index 0000000000000000000000000000000000000000..207577b642507badc1b8064ab2f75c51130e58dd Binary files /dev/null and b/zh-cn/application-dev/ui/figures/mainStart.png differ diff --git a/zh-cn/application-dev/ui/figures/offset.gif b/zh-cn/application-dev/ui/figures/offset.gif new file mode 100644 index 0000000000000000000000000000000000000000..13d5614f4cfa0ede034e44f9fc333b1d55e891ff Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset.gif differ diff --git a/zh-cn/application-dev/ui/figures/offset1.png b/zh-cn/application-dev/ui/figures/offset1.png new file mode 100644 index 0000000000000000000000000000000000000000..e760daef7809d60e1c7b9323bffc267f592c8fc5 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset1.png differ diff --git a/zh-cn/application-dev/ui/figures/offset2.gif b/zh-cn/application-dev/ui/figures/offset2.gif new file mode 100644 index 0000000000000000000000000000000000000000..b517e892ed6ff4ad337e57d044aa518ff78a8792 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/offset2.gif differ diff --git a/zh-cn/application-dev/ui/figures/order1.png b/zh-cn/application-dev/ui/figures/order1.png new file mode 100644 index 0000000000000000000000000000000000000000..297dea381d85074e91edfb664bac5b8e3151f7bb Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order1.png differ diff --git a/zh-cn/application-dev/ui/figures/order2.gif b/zh-cn/application-dev/ui/figures/order2.gif new file mode 100644 index 0000000000000000000000000000000000000000..315c82e417d240d0624a8206c9adf47c4c0a3ec3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/order2.gif differ diff --git a/zh-cn/application-dev/ui/figures/position.gif b/zh-cn/application-dev/ui/figures/position.gif new file mode 100644 index 0000000000000000000000000000000000000000..67811987caa4b35beaea64da68e7d3786db52a58 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/position.gif differ diff --git a/zh-cn/application-dev/ui/figures/row.png b/zh-cn/application-dev/ui/figures/row.png new file mode 100644 index 0000000000000000000000000000000000000000..d7fced9fe4a9fc618dee88ae95cc2f04a34bb3c3 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/row.png differ diff --git a/zh-cn/application-dev/ui/figures/rowalign.png b/zh-cn/application-dev/ui/figures/rowalign.png new file mode 100644 index 0000000000000000000000000000000000000000..1f87579bb75ea031951dc073f0cd0a3a65698ee6 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowalign.png differ diff --git a/zh-cn/application-dev/ui/figures/rowjustify.png b/zh-cn/application-dev/ui/figures/rowjustify.png new file mode 100644 index 0000000000000000000000000000000000000000..7ed6dfc34d5c3dee1202925b373d5c7b7928c248 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowjustify.png differ diff --git a/zh-cn/application-dev/ui/figures/rowspace.png b/zh-cn/application-dev/ui/figures/rowspace.png new file mode 100644 index 0000000000000000000000000000000000000000..9bf2d2da0b1634d8051214908b83bc5e41f1702d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/rowspace.png differ diff --git a/zh-cn/application-dev/ui/figures/scrollcolumn.gif b/zh-cn/application-dev/ui/figures/scrollcolumn.gif new file mode 100644 index 0000000000000000000000000000000000000000..80ee68958c80502be31ddcecc22f198c14a4c335 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollcolumn.gif differ diff --git a/zh-cn/application-dev/ui/figures/scrollrow.gif b/zh-cn/application-dev/ui/figures/scrollrow.gif new file mode 100644 index 0000000000000000000000000000000000000000..14f3d25cbf137366ce3c2bb93f683d75a9297597 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/scrollrow.gif differ diff --git a/zh-cn/application-dev/ui/figures/span1.png b/zh-cn/application-dev/ui/figures/span1.png new file mode 100644 index 0000000000000000000000000000000000000000..fe59d441c386189694b3185e23279f14c6dd4a97 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span1.png differ diff --git a/zh-cn/application-dev/ui/figures/span2.gif b/zh-cn/application-dev/ui/figures/span2.gif new file mode 100644 index 0000000000000000000000000000000000000000..eba3ab4a41c44642c47f1864858094771043dcc7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/span2.gif differ diff --git a/zh-cn/application-dev/ui/figures/stack1.png b/zh-cn/application-dev/ui/figures/stack1.png new file mode 100644 index 0000000000000000000000000000000000000000..87574a9c72652fdda57f54405b675b622f804479 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack1.png differ diff --git a/zh-cn/application-dev/ui/figures/stack2.png b/zh-cn/application-dev/ui/figures/stack2.png new file mode 100644 index 0000000000000000000000000000000000000000..6a518ad4ac87cc91ef44894d15774cb3d60568d1 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stack2.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottom.png b/zh-cn/application-dev/ui/figures/stackbottom.png new file mode 100644 index 0000000000000000000000000000000000000000..d4a1d76611bb608becded581f24b69b48185d96d Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottom.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomend.png b/zh-cn/application-dev/ui/figures/stackbottomend.png new file mode 100644 index 0000000000000000000000000000000000000000..6f34877f2ed88390eca31bab2370c187d012fd73 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackbottomstart.png b/zh-cn/application-dev/ui/figures/stackbottomstart.png new file mode 100644 index 0000000000000000000000000000000000000000..d6539785544de70d20ce382465974cfb24d955c7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackbottomstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stackcenter.png b/zh-cn/application-dev/ui/figures/stackcenter.png new file mode 100644 index 0000000000000000000000000000000000000000..0ba76abeba693ae3d1654b6b3fbde91661669237 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackcenter.png differ diff --git a/zh-cn/application-dev/ui/figures/stackend.png b/zh-cn/application-dev/ui/figures/stackend.png new file mode 100644 index 0000000000000000000000000000000000000000..2bf91c717a94ce47a2f3c9ca766eb89fae513a71 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackend.png differ diff --git a/zh-cn/application-dev/ui/figures/stackstart.png b/zh-cn/application-dev/ui/figures/stackstart.png new file mode 100644 index 0000000000000000000000000000000000000000..3936627a8d4134acd3e02833cb2c3c593f52c66e Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stackstart.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktop.png b/zh-cn/application-dev/ui/figures/stacktop.png new file mode 100644 index 0000000000000000000000000000000000000000..01a649049c24df96510727918689455ad9898559 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktop.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopend.png b/zh-cn/application-dev/ui/figures/stacktopend.png new file mode 100644 index 0000000000000000000000000000000000000000..95e8fef4f2c2a6905ed0efc00e9cacd14852c5de Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopend.png differ diff --git a/zh-cn/application-dev/ui/figures/stacktopstart.png b/zh-cn/application-dev/ui/figures/stacktopstart.png new file mode 100644 index 0000000000000000000000000000000000000000..7b742984076e7066cca56a5647bfa3c096b317f2 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/stacktopstart.png differ diff --git a/zh-cn/application-dev/ui/figures/width.gif b/zh-cn/application-dev/ui/figures/width.gif new file mode 100644 index 0000000000000000000000000000000000000000..34007100b438eb6fc47dd5f48eda6033bc759412 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/width.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif new file mode 100644 index 0000000000000000000000000000000000000000..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif new file mode 100644 index 0000000000000000000000000000000000000000..a7d9b572abb833cc7cd52e63d25c4c261a10af65 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png new file mode 100644 index 0000000000000000000000000000000000000000..25330d63162d9999d2c57d3c33bcc20731df7851 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image1_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif new file mode 100644 index 0000000000000000000000000000000000000000..9dd23bf2e649eb1e9c7a71281a8f26dcd90d6f26 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png index 5accde8bbb1146e3bade9d6cc4d35127dd58b86f..67b8d1571853fe13079a13ed32aff66bc2fc4452 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168410342.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png index b6045521e10cf66733222c0b85b1b65dd20cb66f..ddf24cd804055371cbd8a753089263f6bcc32b79 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001168728872.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png index 546fb29b1f18573353d11d5515f444bf720fcf52..9c89860f26331dc11cf8104711be1ad3be918111 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169678922.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png index a6d0026ba316551ff0819493b84ae8c9cb063289..f910230ebfab9c5315eb1c2bc99f0ca35b3cbe23 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169759552.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif index 0173419db3fd06cc5d328dd6931a2c76664f4596..b59ae3d79b2bc926634a50c1f3f6aecce247763c 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001169918548.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif index 26152ef9f22387729561bdddb9fa7d50019e08cb..c88150c77afccf736d42fe7253df27f2b1d27cd5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170008198.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png new file mode 100644 index 0000000000000000000000000000000000000000..2441a46f00b3083dfaa8ec2dcdb1760aa7e2aeb7 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170167520.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif index b07f4a9f456b5bccab8fe2a2dc997818efad5ddb..a7d9b572abb833cc7cd52e63d25c4c261a10af65 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001170411978.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif index 7d8da86f2f1cf71ca9bc5d6cb65564bb64ae5fd1..16e7ff213bd5caf5a9802001d3ced2996c66e0bc 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png index f6b70b8f1ef886bf8ed6f26e148bddee0b163fd5..60160d18d66fef9a5b65a4c5675fe91873e95582 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204537865.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png index a84303ae2d68affe3f5702317d9f2bf951c90698..b775a2bf408dd710861afa0dfa9f756d5181e811 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204538065.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png index d0e9cf658b9b396873f24666945bb796384c2041..b27a7f5358c954fe7e1bd912358d29d456870c2a 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001204776353.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png index 767315d2f69278028746341e79f88ad179930338..b60416b59cb77e096d615ba1b25d2b14056abe00 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001213968747.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png index 653da4be405165f59cbbe570e9d4d64747fa7495..3f2f15792563ec89015abce1fcf30248b3c0288e 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214128687.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png index aaa0cbf699a302616ce142f43ea3b96df99d75ac..18abb7b725fcf0172f189c0f1cf70e9c5ae31642 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214210217.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png index fb85274edcd9b0a66eaa9e3da3b77e543c048cc8..6a845d64a542809c05f008eef5d1e1ed9d1c22a5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001214998349.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png index 49182b6d8f1c96dcbaac493179fdab3d4b9a7bd4..0a53a5742ac5fda3501a93f576b945e21bd2addf 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215079443.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png index 2923d13dcf52b856158b440de03df929abc4955b..c508bb8764c28f228e2c0a33dd6ee97e48dfe682 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215199399.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif index 8e9c75334361806ac822c8c0f2c377c1679c6ca3..aac78d2abe528a9781e7e07ed2e46a4bf56d7891 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001215318403.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png new file mode 100644 index 0000000000000000000000000000000000000000..68b537c0afc28896fc8d14d36a5d7190fcfa256c Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001224173302.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif index 9e313e1e87059572aa036b06881381da7b070641..0cbcaa3ff368a2a2ad63c8729acc0f66ae874437 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif differ diff --git a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md b/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md deleted file mode 100644 index 86db59447ccb15bad9579553a1eef2e03e143d23..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-component-creation-re-initialization.md +++ /dev/null @@ -1,97 +0,0 @@ -# 组件创建和重新初始化 - -## 初始创建和渲染 - -1. 创建父组件ParentComp; - -2. 本地初始化ParentComp的状态变量isCountDown; - -3. 执行ParentComp的build函数; - -4. 创建Column内置组件; - 1. 创建Text内置组件,设置其文本展示内容,并将Text组件实例添加到Column中; - 2. 判断if条件,创建true分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数创建TimerComponent; - 1. 创建TimerComponent对象; - 2. 本地初始化成员变量初始值; - 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; - 4. 执行TimerComponent的aboutToAppear函数; - 5. 执行TimerComponent的build函数,创建相应的UI描述结构; - 3. 创建Button内置组件,设置相应的内容。 - - -## 状态更新 - -用户单击按钮时: - -1. ParentComp的isCountDown状态变量的值更改为false; - -2. 执行ParentComp的build函数; - -3. Column内置组件会被框架重用并执行重新初始化; - -4. Column的子组件会重用内存中的对象,但会进行重新初始化; - 1. Text内置组件会被重用,但使用新的文本内容进行重新初始化; - 2. 判断if条件,使用false分支上的组件; - 1. 原来true分支上的组件不在使用,这些组件会进行销毁; - 1. 创建的Image内置组件实例进行销毁; - 2. TimerComponent组件实例进行销毁,aboutToDisappear函数被调用; - 2. 创建false分支上的组件; - 1. 创建Image内置组件,并设置其图片源地址; - 2. 使用给定的构造函数重新创建TimerComponent; - 3. 新创建的TimerComponent进行初始化,并调用aboutToAppear函数和build函数。 - 3. Button内置组件会被重用,但使用新的图片源地址。 - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct ParentComp { - @State isCountDown: boolean = true - build() { - Column() { - Text(this.isCountDown ? 'Count Down' : 'Stopwatch') - if (this.isCountDown) { - Image($r("app.media.countdown")).width(200).height(200) - TimerComponent({counter: 10, changePerSec: -1, showInColor: Color.Red}) - } else { - Image($r("app.media.stopwatch")).width(200).height(200) - TimerComponent({counter: 0, changePerSec: +1, showInColor: Color.Black }) - } - Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') - .onClick(() => {this.isCountDown = !this.isCountDown}) - } - } -} - -// Manage and display a count down / stop watch timer -@Component -struct TimerComponent { - @State counter: number = 0 - private changePerSec: number = -1 - private showInColor: Color = Color.Black - private timerId : number = -1 - - build() { - Text(`${this.counter}sec`) - .fontColor(this.showInColor) - } - - aboutToAppear() { - this.timerId = setInterval(() => {this.counter += this.changePerSec}, 1000) - } - - aboutToDisappear() { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } -} -``` - -![](figures/zh-cn_image_0000001118642023.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ts-custom-component-initialization.md b/zh-cn/application-dev/ui/ts-custom-component-initialization.md deleted file mode 100644 index 1433542af3203e3a54f6d883ef099b8f5438f52f..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-initialization.md +++ /dev/null @@ -1,125 +0,0 @@ -# 自定义组件成员变量初始化 - -组件的成员变量可以通过两种方式初始化: - - -- 本地初始化,例如: - ```ts - @State counter: Counter = new Counter() - ``` - -- 在构造组件时通过构造参数初始化,例如: - ```ts - MyComponent({counter: $myCounter}) - ``` - - -具体允许哪种方式取决于状态变量的装饰器: - - -| 装饰器类型 | 本地初始化 | 通过构造函数参数初始化 | -| ------------ | ----- | ----------- | -| @State | 必须 | 可选 | -| @Prop | 禁止 | 必须 | -| @Link | 禁止 | 必须 | -| @StorageLink | 必须 | 禁止 | -| @StorageProp | 必须 | 禁止 | -| @Provide | 必须 | 可选 | -| @Consume | 禁止 | 禁止 | -| @ObjectLink | 禁止 | 必须 | -| 常规成员变量 | 推荐 | 可选 | - - -从上表中可以看出: - - -- @State变量需要本地初始化,初始化的值可以被构造参数覆盖; - -- @Prop和@Link变量必须且仅通过构造函数参数进行初始化。 - - -通过构造函数方法初始化成员变量,需要遵循如下规则: - - -| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 | -| ---------------------- | ------ | ----- | ----- | ---- | -| @State | 不允许 | 允许 | 允许 | 允许 | -| @Link | 不允许 | 允许 | 不推荐 | 允许 | -| @Prop | 不允许 | 不允许 | 允许 | 允许 | -| @StorageLink | 不允许 | 允许 | 不允许 | 允许 | -| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 | -| 常规变量 | 允许 | 不允许 | 不允许 | 允许 | - - -从上表中可以看出: - - -- 父组件的常规变量可以用于初始化子组件的@State变量,但不能用于初始化@Link或@Prop变量。 - -- 父组件的@State变量可以初始化子组件的@Prop、@Link(通过$)或常规变量,但不能初始化子组件的@State变量。 - -- 父组件的@Link变量可以初始化子组件的@Link或常规变量。但是初始化子组件的@State成员是语法错误,此外不建议初始化@prop。 - -- 父组件的@Prop变量可以初始化子组件的常规变量或@Prop变量,但不能初始化子组件的@State或@Link变量。 - -- @StorageLink和@StorageProp不允许由父组件中传递到子组件。 - -- 除了上述规则外,还需要遵循TS的强类型规则。 - - -## 示例 - -```ts -// xxx.ets -class ClassA { - public a:number - constructor(a: number) { - this.a = a - } -} -@Entry -@Component -struct Parent { - @State parentState: ClassA = new ClassA(1) - - build() { - Column() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(2), aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aLink: $parentState }) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - CompA({ aState: new ClassA(3), aLink: $parentState }) - } - } - } -} - -@Component -struct CompA { - @State aState: any = false - @Link aLink: ClassA - - build() { - Column() { - CompB({ bLink: $aLink, bProp: this.aState }) - CompB({ bLink: $aState, bProp: false }) - } - } -} - -@Component -struct CompB { - @Link bLink: ClassA - @Prop bProp: boolean - - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Text(JSON.stringify(this.bLink.a)).fontSize(30) - Text(JSON.stringify(this.bProp)).fontSize(30).fontColor(Color.Red) - }.margin(10) - } -} -``` diff --git a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md deleted file mode 100644 index 5a0126b00ae83f1e41792a2d60aa5032e5131525..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-custom-component-lifecycle-callbacks.md +++ /dev/null @@ -1,57 +0,0 @@ -# 自定义组件生命周期回调函数 - -自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 - - -## 生命周期回调函数定义 - -| 函数名 | 描述 | -| ---------------- | ------------------------------------------------------------ | -| aboutToAppear | 函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 | -| aboutToDisappear | 函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 | -| onPageShow | 页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onPageHide | 页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 | -| onBackPress | 当用户点击返回按钮时触发,仅\@Entry修饰的自定义组件生效。
- 返回true表示页面自己处理返回逻辑, 不进行页面路由。
- 返回false表示使用默认的返回逻辑。
- 不返回值会作为false处理。 | -| onMeasure9+ | 框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量 | -| onLayout9+ | 框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量 | - - -## 示例 - -```ts -// xxx.ets -@Entry -@Component -struct CountDownTimerComponent { - @State countDownFrom: number = 10 - private timerId: number = -1 - - aboutToAppear(): void { - this.timerId = setInterval(() => { - if (this.countDownFrom <= 1) { - clearTimeout(this.timerId) - } - this.countDownFrom -= 1 - }, 1000) // decr counter by 1 every second - } - - aboutToDisappear(): void { - if (this.timerId > 0) { - clearTimeout(this.timerId) - this.timerId = -1 - } - } - - build() { - Text(`${this.countDownFrom} sec left`) - } -} -``` - -上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 - - -> **说明:** -> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; -> -> - 不允许在生命周期函数中使用async await。 diff --git a/zh-cn/application-dev/ui/ts-framework-directory.md b/zh-cn/application-dev/ui/ts-framework-directory.md deleted file mode 100644 index b20e3023475a0ced28afa89fb94ad2f02a75e077..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-framework-directory.md +++ /dev/null @@ -1,38 +0,0 @@ -# 目录结构 - - -FA应用的ArkTS模块(entry/src/main)的典型开发目录结构如下: - - -![zh-cn_image_0000001182200571](figures/zh-cn_image_0000001182200571.png) - - -**目录结构中文件分类如下:** - - -.ets结尾的ArkTS文件,用于描述UI布局、样式、事件交互和页面逻辑。 - -**各个文件夹和文件的作用:** - -- **app.ets**文件用于全局应用逻辑和应用生命周期管理。 - -- **pages**目录用于存放所有页面。 - -- **common**目录用于存放公共代码文件,比如:自定义组件和公共方法。 - - -> **说明:** -> -> - 资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源文件的分类](ui-ts-basic-resource-file-categories.md)。 ->- 页面支持导入TypeScript和JavaScript文件。 - -**js标签配置:** - - 开发框架需要在配置文件中标识相关的js标签,其中的每个元素代表一个JS模块的信息,包含了实例名称、页面路由、视图窗口等。 - - -> **说明:** -> -> FA模型请参考 [表22 js对象的内部结构说明](../quick-start/package-structure.md#module对象的内部结构)。 -> -> Stage模型请参考 [表3 module对象内部结构说明](../quick-start/stage-structure.md#module对象内部结构)。 diff --git a/zh-cn/application-dev/ui/ts-resource-access.md b/zh-cn/application-dev/ui/ts-resource-access.md deleted file mode 100644 index 5ab95b5eba3fbf1a325dea0b9f6fdd7a10ba6193..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ts-resource-access.md +++ /dev/null @@ -1,154 +0,0 @@ -# 资源访问 - - -## 访问应用资源 - -在工程中,通过```"$r('app.type.name')"```的形式引用应用资源。app代表是应用内resources目录中定义的资源;type代表资源类型(或资源的存放位置),可以取“color”、“float”、“string”、“plural”、“media”,name代表资源命名,由开发者定义资源时确定。 - -引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。 - -> **说明:** -> -> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。 -> -> `$r`返回值为Resource对象,可通过[getString](../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。 - -在xxx.ets文件中,可以使用在resources目录中定义的资源。 - -```ts -Text($r('app.string.string_hello')) - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.string.string_world')) - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Text($r('app.string.message_arrive', "five of the clock")) // 引用string资源,$r的第二个参数用于替换%s - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.plural.eat_apple', 5, 5)) // plural$r引用,第一个指定plural资源,第二个参数指定单复数的数量,此处第三个数字为对%d的替换 - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Image($r('app.media.my_background_image')) // media资源的$r引用 - -Image($rawfile('test.png')) // rawfile$r引用rawfile目录下图片 - -Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下图片 -``` -## 访问系统资源 - -系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。 - - -开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。 - -```ts -Text('Hello') - .fontColor($r('sys.color.ohos_id_color_emphasize')) - .fontSize($r('sys.float.ohos_id_text_size_headline1')) - .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) - .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) -Image($r('sys.media.ohos_app_icon')) - .border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2}) - .margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) - .height(200) - .width(300) -``` -## 资源文件示例 - -color.json文件的内容如下: - - -```json -{ - "color": [ - { - "name": "color_hello", - "value": "#ffff0000" - }, - { - "name": "color_world", - "value": "#ff0000ff" - } - ] -} -``` - -float.json文件的内容如下: - - -```json -{ - "float":[ - { - "name":"font_hello", - "value":"28.0fp" - }, - { - "name":"font_world", - "value":"20.0fp" - } - ] -} -``` - -string.json文件的内容如下: - - -```json -{ - "string":[ - { - "name":"string_hello", - "value":"Hello" - }, - { - "name":"string_world", - "value":"World" - }, - { - "name":"message_arrive", - "value":"We will arrive at %s." - } - ] -} -``` - -plural.json文件的内容如下: - - -```json -{ - "plural":[ - { - "name":"eat_apple", - "value":[ - { - "quantity":"one", - "value":"%d apple" - }, - { - "quantity":"other", - "value":"%d apples" - } - ] - } - ] -} -``` - - - - -## 相关实例 - -针对访问应用资源,有以下相关实例可供参考: - -- [`ResourceManager`:资源管理器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-event.md b/zh-cn/application-dev/ui/ui-js-building-ui-event.md index 9c09ebb86f3b0a6177307deb7d7cd6b5ebca2bc2..e1aa990223059ba6190c147f6753e5fc48de85d7 100755 --- a/zh-cn/application-dev/ui/ui-js-building-ui-event.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-event.md @@ -48,16 +48,18 @@ longpress:用户在相同位置长时间保持与屏幕接触。 ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; } .text-container { - margin-top: 10px; + margin-top: 30px; flex-direction: column; - width: 750px; - height: 50px; - background-color: #09ba07; + width: 600px; + height: 70px; + background-color: #0000FF; } .text-style { width: 100%; @@ -99,3 +101,5 @@ export default { }, } ``` + +![zh-cn_image_00000011](figures/zh-cn_image_00000011.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-js-components-canvas.md b/zh-cn/application-dev/ui/ui-js-components-canvas.md index c46363421b6eddd6b9c6376feb171017c0f39126..9410a9d4ceda10a4fd7cb2169ca71afe7ec51a6c 100644 --- a/zh-cn/application-dev/ui/ui-js-components-canvas.md +++ b/zh-cn/application-dev/ui/ui-js-components-canvas.md @@ -118,8 +118,6 @@ import prompt from '@system.prompt'; export default { data:{ dataURL:null, - antialia: false, - porc:'open', }, onShow(){ let el = this.$refs.canvas1; diff --git a/zh-cn/application-dev/ui/ui-js-components-marquee.md b/zh-cn/application-dev/ui/ui-js-components-marquee.md index f711b61e755f78da710ee8d41f987845a4b78fe8..f755e9807c056a25788fb999e9826f9c80f8bf67 100644 --- a/zh-cn/application-dev/ui/ui-js-components-marquee.md +++ b/zh-cn/application-dev/ui/ui-js-components-marquee.md @@ -79,7 +79,7 @@ marquee通过color和font-weight属性设置跑马灯中文本的颜色、字体
- It's a racing lamp + Life is a journey, not the destination.
@@ -128,7 +128,9 @@ button{ // xxx.js export default { private: { - loopval: -1, scroll: 10, isleft: "left", + loopval: -1, + scroll: 10, + isleft: "left", }, onInit(){ }, @@ -163,7 +165,7 @@ export default {
- It's a racing lamp + Life is a journey, not the destination.
diff --git a/zh-cn/application-dev/ui/ui-js-components-search.md b/zh-cn/application-dev/ui/ui-js-components-search.md index 5c712126e14d8c24c396dd84808e4bdcae395564..85bd2730eec8c3f7a8391c608f9f42f179407ed4 100644 --- a/zh-cn/application-dev/ui/ui-js-components-search.md +++ b/zh-cn/application-dev/ui/ui-js-components-search.md @@ -62,7 +62,7 @@ ## 添加样式 -通过color、placeholder和caret-color样式来设置搜索框的文本颜色、提示文本颜色和光标颜色。 +通过color、placeholder-color和caret-color样式来设置搜索框的文本颜色、提示文本颜色和光标颜色。 ```html @@ -84,7 +84,9 @@ background-color: #F1F3F5; } search{ - color: black; placeholder-color: black; caret-color: red; + color: black; + placeholder-color: black; + caret-color: red; } ``` diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..16869cea7b746874566257d31d4e9448d0a3967f --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -0,0 +1,343 @@ +# 添加动画效果 + +动画主要包含了组件动画和页面间动画,并提供了[插值计算](../reference/apis/js-apis-curve.md)和[矩阵变换](../reference/apis/js-apis-matrix4.md)的动画能力接口,让开发者极大程度的自主设计动画效果。 + +在本节主要完成两个动画效果: + +1. 启动页的闪屏动画,即Logo图标的渐出和放大效果; +2. 食物列表页和食物详情页的共享元素转场动画效果。 + +## animateTo实现闪屏动画 + +组件动画包括属性动画和animateTo显式动画: + +1. 属性动画:设置组件通用属性变化的动画效果。 +2. 显式动画:设置组件从状态A到状态B的变化动画效果,包括样式、位置信息和节点的增加删除等,开发者无需关注变化过程,只需指定起点和终点的状态。animateTo还提供播放状态的回调接口,是对属性动画的增强与封装。 + +闪屏页面的动画效果是Logo图标的渐出和放大,动画结束后跳转到食物分类列表页面。接下来,我们就使用animateTo来实现启动页动画的闪屏效果。 + +1. 动画效果自动播放。闪屏动画的预期效果是,进入Logo页面后,animateTo动画效果自动开始播放,可以借助于组件显隐事件的回调接口来实现。调用Shape的onAppear方法,设置其显式动画。 + + ```ts + Shape() { + ... + } + .onAppear(() => { + animateTo() + }) + ``` + +2. 创建opacity和scale数值的成员变量,用装饰器@State修饰。表示其为有状态的数据,即改变会触发页面的刷新。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo() + }) + } + } + ``` + +3. 设置animateTo的动画曲线curve。Logo的加速曲线为先慢后快,使用贝塞尔曲线cubicBezier,cubicBezier(0.4, 0, 1, 1)。 + + 需要使用动画能力接口中的插值计算,首先要导入curves模块。 + + ```ts + import Curves from '@ohos.curves' + ``` + + @ohos.curves模块提供了线性Curve. Linear、阶梯step、三阶贝塞尔(cubicBezier)和弹簧(spring)插值曲线的初始化函数,可以根据入参创建一个插值曲线对象。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + curve: this.curve1 + }) + }) + } + } + ``` + +4. 设置动画时长为1s,延时0.1s开始播放,设置显示动效event的闭包函数,即起点状态到终点状态为透明度opacityValue和大小scaleValue从0到1,实现Logo的渐出和放大效果。 + + ```ts + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + +5. 闪屏动画播放结束后定格1s,进入FoodCategoryList页面。设置animateTo的onFinish回调接口,调用定时器Timer的setTimeout接口延时1s后,调用router.replace,显示FoodCategoryList页面。 + + ```ts + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + + build() { + Shape() { + ... + } + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + } + } + ``` + + 整体代码如下。 + + ```ts + import Curves from '@ohos.curves' + import router from '@ohos.router' + + @Entry + @Component + struct Logo { + @State private opacityValue: number = 0 + @State private scaleValue: number = 0 + private curve1 = Curves.cubicBezier(0.4, 0, 1, 1) + private pathCommands1: string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2: string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + .scale({ x: this.scaleValue, y: this.scaleValue }) + .opacity(this.opacityValue) + .onAppear(() => { + animateTo({ + duration: 2000, + curve: this.curve1, + delay: 100, + onFinish: () => { + setTimeout(() => { + router.replace({ url: "pages/FoodCategoryList" }) + }, 1000); + } + }, () => { + this.opacityValue = 1 + this.scaleValue = 1 + }) + }) + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top: 300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top: 4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![animation-feature](figures/animation-feature.gif) + +## 页面转场动画 + +食物分类列表页和食物详情页之间的共享元素转场,即点击FoodListItem/FoodGridItem后,食物缩略图会放大,随着页面跳转,到食物详情页的大图。 + +1. 设置FoodListItem和FoodGridItem的Image组件的共享元素转场方法(sharedTransition)。转场id为foodItem.id,转场动画时长为1s,延时0.1s播放,变化曲线为贝塞尔曲线Curves.cubicBezier(0.2, 0.2, 0.1, 1.0) ,需引入curves模块。 + + 共享转场时会携带当前元素的被设置的属性,所以创建Row组件,使其作为Image的父组件,设置背景颜色在Row上。 + + 在FoodListItem的Image组件上设置autoResize为false,因为image组件默认会根据最终展示的区域,去调整图源的大小,以优化图片渲染性能。在转场动画中,图片在放大的过程中会被重新加载,所以为了转场动画的流畅,autoResize设置为false。 + + ```ts + // FoodList.ets + import Curves from '@ohos.curves' + + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Navigator({ target: 'pages/FoodDetail' }) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(40) + .width(40) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + } + .params({ foodData: this.foodItem }) + .margin({ right: 24, left:32 }) + } + } + + @Component + struct FoodGridItem { + private foodItem: FoodData + build() { + Column() { + Row() { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .autoResize(false) + .height(152) + .width('100%') + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + } + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + .padding({ left: 8 }) + Text(this.foodItem.calories + 'kcal') + .fontSize(14) + .margin({ right: 6 }) + } + .height(32) + .width('100%') + .backgroundColor('#FFe5e5e5') + } + .height(184) + .width('100%') + .onClick(() => { + router.push({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } }) + }) + } + } + + + ``` + +2. 设置FoodDetail页面的FoodImageDisplay的Image组件的共享元素转场方法(sharedTransition)。设置方法同上。 + + ```ts + import Curves from '@ohos.curves' + + @Component + struct FoodImageDisplay { + private foodItem: FoodData + build() { + Stack({ alignContent: Alignment.BottomStart }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .sharedTransition(this.foodItem.id, { duration: 1000, curve: Curves.cubicBezier(0.2, 0.2, 0.1, 1.0), delay: 100 }) + Text(this.foodItem.name) + .fontSize(26) + .fontWeight(500) + .margin({ left: 26, bottom: 17.4 }) + } + .height(357) + } + } + ``` + + ![animation-feature1](figures/animation-feature1.gif) + + 通过对绘制组件和动画的学习,我们已完成了启动Logo的绘制、启动页动画和页面间的转场动画,声明式UI框架提供了丰富的动效接口,合理地应用和组合可以让应用更具有设计感。 + + diff --git a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md b/zh-cn/application-dev/ui/ui-ts-basic-components-button.md deleted file mode 100644 index 06ff221c14b45531dc919dca123e6d1ac28f5b43..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md +++ /dev/null @@ -1,193 +0,0 @@ -# Button - - -Button是按钮组件,通常用于响应用户的点击操作,如提交表单,其类型包括胶囊按钮、圆形按钮、普通按钮。具体用法请参考[Button](../reference/arkui-ts/ts-basic-components-button.md)。 - - -## 创建按钮 - -Button通过调用接口来创建,接口调用有以下两种形式: - -- 创建包含子组件的按钮 - - `Button(options?: {type?: ButtonType, stateEffect?: boolean})`,该接口用于创建包含子组件的按钮,其中type用于设置Button类型,stateEffect属性设置Button是否开启点击效果。 - - ``` - Button({ type: ButtonType.Normal, stateEffect: true }) { - Row() { - Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 }) - Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 }) - }.alignItems(VerticalAlign.Center) - }.borderRadius(8).backgroundColor(0x317aff).width(90) - ``` - - - ![zh-cn_image_0000001260555857](figures/zh-cn_image_0000001260555857.png) - -- 创建不包含子组件的按钮 - - `Button(label?: string, options?: { type?: ButtonType, stateEffect?: boolean })`,该接口用于创建不包含子组件的按钮,其中label确定所创建的Button是否包含子组件。 - - ``` - Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .borderRadius(8) - .backgroundColor(0x317aff) - .width(90) - ``` - - - ![zh-cn_image_0000001215796030](figures/zh-cn_image_0000001215796030.png) - - -## 设置按钮类型 - -Button有三种可选类型,分别为Capsule(胶囊类型)、Circle(圆形按钮)和Normal(普通按钮),通过type进行设置。 - -- 胶囊按钮(默认类型) - - ```ts - Button('Disable', { type: ButtonType.Capsule, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - ``` - - ![zh-cn_image_0000001215645452](figures/zh-cn_image_0000001215645452.png) - -- 圆形按钮 - - ```ts - Button('Circle', { type: ButtonType.Circle, stateEffect: false }) - .backgroundColor(0x317aff) - .width(90) - .height(90) - ``` - - ![zh-cn_image_0000001215965420](figures/zh-cn_image_0000001215965420.png) - - -## 自定义样式 - -- 设置边框弧度 - 一般使用通用属性来自定义按钮样式。例如通过borderRadius属性设置按钮的边框弧度。 - - - ```ts - Button('circle border', { type: ButtonType.Normal }) - .borderRadius(20) - ``` - - ![zh-cn_image_0000001190463780](figures/zh-cn_image_0000001190463780.png) - -- 设置文本样式 - 通过添加文本样式设置按钮文本的展示样式。 - - - ```ts - Button('font style', { type: ButtonType.Normal }) - .fontSize(20) - .fontColor(Color.Red) - .fontWeight(800) - ``` - - ![zh-cn_image_0000001189744672](figures/zh-cn_image_0000001189744672.png) - -- 设置背景颜色 - 添加backgroundColor属性设置按钮的背景颜色。 - - - ```ts - Button('background color').backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001235146483](figures/zh-cn_image_0000001235146483.png) - -- 用作功能型按钮 - 为删除操作创建一个按钮。 - - - ```ts - Button({ type: ButtonType.Circle, stateEffect: true }) { - Image($r('app.media.ic_public_delete_filled')).width(30).height(30) - }.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42) - ``` - - ![zh-cn_image_0000001260373911](figures/zh-cn_image_0000001260373911.png) - - -## 添加事件 - -Button组件通常用于触发某些操作,可以在绑定onClick事件来响应点击操作后的自定义行为。 - - -```ts -Button('Ok', { type: ButtonType.Normal, stateEffect: true }) - .onClick(()=>{ - console.info('Button onClick') - }) -``` - - -## 场景示例 - -- 用于启动操作 - - 可以将按钮用于启动操作的任何用户界面元素。按钮会根据用户的操作触发相应的事件。如,在List容器里边通过点击按钮进行页面跳转: - - ```ts - // xxx.ets - import router from '@ohos.router' - - @Entry - @Component - struct ButtonCase1 { - build() { - List({ space: 4 }) { - ListItem() { - Button("First").onClick(() => { - router.push({ url: 'xxx' }) - }) - } - - ListItem() { - Button("Second").onClick(() => { - router.push({ url: 'yyy' }) - }) - } - - ListItem() { - Button("Third").onClick(() => { - router.push({ url: 'zzz' }) - }) - } - } - .listDirection(Axis.Vertical) - .backgroundColor(0xDCDCDC).padding(20) - } - } - ``` - - -​ ![zh-cn_image_0000001235626467](figures/zh-cn_image_0000001235626467.png) - - -- 用于表单的提交 - - 在用户登录/注册页面,用户的登录或注册的提交操作会用按钮。 - - ```ts - // xxx.ets - @Entry - @Component - struct ButtonCase2 { - build() { - Column() { - TextInput({ placeholder: 'input your username' }).margin({ top: 20 }) - TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 }) - Button('Register').width(300).margin({ top: 20 }) - }.padding(20) - } - } - ``` - - - ![zh-cn_image_0000001190466492](figures/zh-cn_image_0000001190466492.png) diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md index 1f8e88029e8a192fbed74060f3c72d1e21d2357b..8df2f7bd9c6d81a5fe9778a3cfeca9185e19f19c 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-grid-layout.md @@ -1,16 +1,16 @@ # 构建食物分类Grid布局 - - 健康饮食应用在主页提供给用户两种食物显示方式:列表显示和网格显示。开发者将实现通过页签切换不同食物分类的网格布局。 1. 将Category枚举类型引入FoodCategoryList页面。 + ```ts import { Category, FoodData } from '../model/FoodData' ``` 2. 创建FoodCategoryList和FoodCategory组件,其中FoodCategoryList作为新的页面入口组件,在入口组件调用initializeOnStartup方法。 + ```ts @Component struct FoodList { @@ -19,7 +19,7 @@ ...... } } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -27,7 +27,7 @@ ...... } } - + @Entry @Component struct FoodCategoryList { @@ -39,13 +39,14 @@ ``` 3. 在FoodCategoryList组件内创建showList成员变量,用于控制List布局和Grid布局的渲染切换。需要用到条件渲染语句if...else...。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack() { if (this.showList) { @@ -59,13 +60,14 @@ ``` 4. 在页面右上角创建切换List/Grid布局的图标。设置Stack对齐方式为顶部尾部对齐TopEnd,创建Image组件,设置其点击事件,即showList取反。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -85,14 +87,15 @@ } ``` -5. 添加\@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 +5. 添加@State装饰器。点击右上角的switch标签后,页面没有任何变化,这是因为showList不是有状态数据,它的改变不会触发页面的刷新。需要为其添加\@State装饰器,使其成为状态数据,它的改变会引起其所在组件的重新渲染。 + ```ts @Entry @Component struct FoodCategoryList { private foodItems: FoodData[] = initializeOnStartup() @State private showList: boolean = false - + build() { Stack({ alignContent: Alignment.TopEnd }) { if (this.showList) { @@ -110,7 +113,7 @@ }.height('100%') } } - + ``` 点击切换图标,FoodList组件出现,再次点击,FoodList组件消失。 @@ -118,6 +121,7 @@ ![zh-cn_image_0000001170411978](figures/zh-cn_image_0000001170411978.gif) 6. 创建显示所有食物的页签(All)。在FoodCategory组件内创建Tabs组件和其子组件TabContent,设置tabBar为All。设置TabBars的宽度为280,布局模式为Scrollable,即超过总长度后可以滑动。Tabs是一种可以通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图TabContent。 + ```ts @Component struct FoodCategory { @@ -137,13 +141,14 @@ ![zh-cn_image_0000001204538065](figures/zh-cn_image_0000001204538065.png) 7. 创建FoodGrid组件,作为TabContent的子组件。 + ```ts @Component struct FoodGrid { private foodItems: FoodData[] build() {} } - + @Component struct FoodCategory { private foodItems: FoodData[] @@ -162,6 +167,7 @@ ``` 8. 实现2 \* 6的网格布局(一共12个食物数据资源)。创建Grid组件,设置列数columnsTemplate('1fr 1fr'),行数rowsTemplate('1fr 1fr 1fr 1fr 1fr 1fr'),行间距和列间距rowsGap和columnsGap为8。创建Scroll组件,使其可以滑动。 + ```ts @Component struct FoodGrid { @@ -185,6 +191,7 @@ ``` 9. 创建FoodGridItem组件,展示食物图片、名称和卡路里,实现其UI布局,为GridItem的子组件。每个FoodGridItem高度为184,行间距为8,设置Grid总高度为(184 + 8) \* 6 - 8 = 1144。 + ```ts @Component struct FoodGridItem { @@ -196,7 +203,7 @@ .objectFit(ImageFit.Contain) .height(152) .width('100%') - }.backgroundColor('#FFf1f3f5') + } Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text(this.foodItem.name) .fontSize(14) @@ -214,7 +221,7 @@ .width('100%') } } - + @Component struct FoodGrid { private foodItems: FoodData[] @@ -239,123 +246,126 @@ } ``` - ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.gif) + ![zh-cn_image_0000001170167520](figures/zh-cn_image_0000001170167520.png) 10. 创建展示蔬菜(Category.Vegetable)、水果(Category.Fruit)、坚果(Category.Nut)、海鲜(Category.SeaFood)和甜品(Category.Dessert)分类的页签。 - ```ts - @Component - struct FoodCategory { - private foodItems: FoodData[] - build() { - Stack() { - Tabs() { - TabContent() { - FoodGrid({ foodItems: this.foodItems }) - }.tabBar('All') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) - }.tabBar('Vegetable') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) - }.tabBar('Fruit') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) - }.tabBar('Nut') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) - }.tabBar('Seafood') - - TabContent() { - FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) - }.tabBar('Dessert') + + ```ts + @Component + struct FoodCategory { + private foodItems: FoodData[] + + build() { + Stack() { + Tabs() { + TabContent() { + FoodGrid({ foodItems: this.foodItems }) + }.tabBar('All') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Vegetable)) }) + }.tabBar('Vegetable') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Fruit)) }) + }.tabBar('Fruit') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Nut)) }) + }.tabBar('Nut') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Seafood)) }) + }.tabBar('Seafood') + + TabContent() { + FoodGrid({ foodItems: this.foodItems.filter(item => (item.category === Category.Dessert)) }) + }.tabBar('Dessert') + } + .barWidth(280) + .barMode(BarMode.Scrollable) } - .barWidth(280) - .barMode(BarMode.Scrollable) } } - } - ``` + ``` 11. 设置不同食物分类的Grid的行数和高度。因为不同分类的食物数量不同,所以不能用'1fr 1fr 1fr 1fr 1fr 1fr '常量来统一设置成6行。 创建gridRowTemplate和HeightValue成员变量,通过成员变量设置Grid行数和高度。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` - - 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - - ```ts - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - ``` - - 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + 调用aboutToAppear接口计算行数(gridRowTemplate )和高度(heightValue)。 - ```ts - @Component - struct FoodGrid { - private foodItems: FoodData[] - private gridRowTemplate : string = '' - private heightValue: number - - aboutToAppear() { - var rows = Math.round(this.foodItems.length / 2); - this.gridRowTemplate = '1fr '.repeat(rows); - this.heightValue = rows * 192 - 8; - } - - build() { - Scroll() { - Grid() { - ForEach(this.foodItems, (item: FoodData) => { - GridItem() { - FoodGridItem({foodItem: item}) - } - }, (item: FoodData) => item.id.toString()) - } - .rowsTemplate(this.gridRowTemplate) - .columnsTemplate('1fr 1fr') - .columnsGap(8) - .rowsGap(8) - .height(this.heightValue) - } - .scrollBar(BarState.Off) - .padding({left: 16, right: 16}) - } - } - ``` + ```ts + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + ``` + + 自定义组件提供了两个生命周期的回调接口aboutToAppear和aboutToDisappear。aboutToAppear的执行时机在创建自定义组件后,执行自定义组件build方法之前。aboutToDisappear在自定义组件销毁之前的时机执行。 + + ![zh-cn_image_0000001215113569](figures/zh-cn_image_0000001215113569.png) + + ```ts + @Component + struct FoodGrid { + private foodItems: FoodData[] + private gridRowTemplate: string = '' + private heightValue: number + + aboutToAppear() { + var rows = Math.round(this.foodItems.length / 2); + this.gridRowTemplate = '1fr '.repeat(rows); + this.heightValue = rows * 192 - 8; + } + + build() { + Scroll() { + Grid() { + ForEach(this.foodItems, (item: FoodData) => { + GridItem() { + FoodGridItem({ foodItem: item }) + } + }, (item: FoodData) => item.id.toString()) + } + .rowsTemplate(this.gridRowTemplate) + .columnsTemplate('1fr 1fr') + .columnsGap(8) + .rowsGap(8) + .height(this.heightValue) + } + .scrollBar(BarState.Off) + .padding({ left: 16, right: 16 }) + } + } + ``` - ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) + ![zh-cn_image_0000001170008198](figures/zh-cn_image_0000001170008198.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md index bb5ab8da2f5078e85109101f3f0a07257e609f40..5201e0e720b83083b0ceaeaac73ca95d15ed9290 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md +++ b/zh-cn/application-dev/ui/ui-ts-building-category-list-layout.md @@ -1,23 +1,12 @@ # 构建食物列表List布局 - - 使用List组件和ForEach循环渲染,构建食物列表布局。 -1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets,并将其添加到config.json文件下的pages标签,位于第一序位的页面为首页。 - ```json - "js": [ - { - "pages": [ - "pages/FoodCategoryList", - "pages/FoodDetail" - ], - ] - ``` - +1. 在pages目录新建页面FoodCategoryList.ets,将index.ets改名为FoodDetail.ets。 + 2. 新建FoodList组件作为页面入口组件,FoodListItem为其子组件。List组件是列表组件,适用于重复同类数据的展示,其子组件为ListItem,适用于展示列表中的单元。 - ``` + ```ts @Component struct FoodListItem { build() {} @@ -43,7 +32,7 @@ ``` 4. FoodList和FoodListItem组件数值传递。在FoodList组件内创建类型为FoodData[]成员变量foodItems,调用initializeOnStartup方法为其赋值。在FoodListItem组件内创建类型为FoodData的成员变量foodItem。将父组件foodItems数组的第一个元素的foodItems[0]作为参数传递给FoodListItem。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' @@ -68,20 +57,64 @@ ``` 5. 声明子组件FoodListItem 的UI布局。创建Flex组件,包含食物图片缩略图,食物名称,和食物对应的卡路里。 - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' + @Component + struct FoodListItem { + private foodItem: FoodData + build() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Image(this.foodItem.image) + .objectFit(ImageFit.Contain) + .height(40) + .width(40) + .margin({ right: 16 }) + Text(this.foodItem.name) + .fontSize(14) + .flexGrow(1) + Text(this.foodItem.calories + ' kcal') + .fontSize(14) + } + .height(64) + .margin({ right: 24, left:32 }) + } + } + + @Entry + @Component + struct FoodList { + private foodItems: FoodData[] = initializeOnStartup() + build() { + List() { + ListItem() { + FoodListItem({ foodItem: this.foodItems[0] }) + } + } + } + } + ``` + + + ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) + +6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 + + ```ts + import { FoodData } from '../model/FoodData' + import { initializeOnStartup } from '../model/FoodDataModels' + @Component struct FoodListItem { private foodItem: FoodData + build() { Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) .width(40) - .backgroundColor('#FFf1f3f5') .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -90,62 +123,21 @@ .fontSize(14) } .height(64) - .margin({ right: 24, left:32 }) + .margin({ right: 24, left: 32 }) } } - - @Entry - @Component - struct FoodList { - private foodItems: FoodData[] = initializeOnStartup() - build() { - List() { - ListItem() { - FoodListItem({ foodItem: this.foodItems[0] }) - } - } - } - } - ``` - - ![zh-cn_image_0000001204776353](figures/zh-cn_image_0000001204776353.png) - -6. 创建两个FoodListItem。在List组件创建两个FoodListItem,分别给FoodListItem传递foodItems数组的第一个元素this.foodItems[0]和第二个元素foodItem: this.foodItems[1]。 - ``` - import { FoodData } from '../model/FoodData' - import { initializeOnStartup } from '../model/FoodDataModels' - - @Component - struct FoodListItem { - private foodItem: FoodData - build() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { - Image(this.foodItem.image) - .objectFit(ImageFit.Contain) - .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') - .margin({ right: 16 }) - Text(this.foodItem.name) - .fontSize(14) - .flexGrow(1) - Text(this.foodItem.calories + ' kcal') - .fontSize(14) - } - .height(64) - .margin({ right: 24, left:32 }) - } - } - + @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { List() { ListItem() { FoodListItem({ foodItem: this.foodItems[0] }) } + ListItem() { FoodListItem({ foodItem: this.foodItems[1] }) } @@ -153,36 +145,16 @@ } } ``` + + + ![zh-cn_image1_0000001204776353](figures/zh-cn_image1_0000001204776353.png) + +7. 单独创建每一个FoodListItem肯定是不合理的,这就需要引入[ForEach循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)。 - ![zh-cn_image_0000001204537865](figures/zh-cn_image_0000001204537865.png) - -7. 单独创建每一个FoodListItem肯定是不合理的。这就需要引入ForEach循环渲染,ForEach语法如下。 - ``` - ForEach( - arr: any[], // Array to be iterated - itemGenerator: (item: any) => void, // child component generator - keyGenerator?: (item: any) => string // (optional) Unique key generator, which is recommended. - ) - ``` - - ForEach组有三个参数,第一个参数是需要被遍历的数组,第二个参数为生成子组件的lambda函数,第三个参数是键值生成器。出于性能原因,即使第三个参数是可选的,强烈建议开发者提供。keyGenerator使开发框架能够更好地识别数组更改,而不必因为item的更改重建全部节点。 - - 遍历foodItems数组循环创建ListItem组件,foodItems中每一个item都作为参数传递给FoodListItem组件。 - - ``` - ForEach(this.foodItems, item => { - ListItem() { - FoodListItem({ foodItem: item }) - } - }, item => item.id.toString()) - ``` - - 整体的代码如下。 - - ``` + ```ts import { FoodData } from '../model/FoodData' import { initializeOnStartup } from '../model/FoodDataModels' - + @Component struct FoodListItem { private foodItem: FoodData @@ -191,8 +163,7 @@ Image(this.foodItem.image) .objectFit(ImageFit.Contain) .height(40) - .width(40) - .backgroundColor('#FFf1f3f5') + .width(40) .margin({ right: 16 }) Text(this.foodItem.name) .fontSize(14) @@ -204,7 +175,7 @@ .margin({ right: 24, left:32 }) } } - + @Entry @Component struct FoodList { @@ -220,22 +191,25 @@ } } ``` - + 8. 添加FoodList标题。 + ``` @Entry @Component struct FoodList { private foodItems: FoodData[] = initializeOnStartup() + build() { Column() { - Flex({justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center}) { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text('Food List') .fontSize(20) - .margin({ left:20 }) + .margin({ left: 20 }) } .height('7%') .backgroundColor('#FFf1f3f5') + List() { ForEach(this.foodItems, item => { ListItem() { @@ -249,4 +223,4 @@ } ``` - ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) + ![zh-cn_image_0000001169678922](figures/zh-cn_image_0000001169678922.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-building-data-model.md b/zh-cn/application-dev/ui/ui-ts-building-data-model.md index b0627fe491d6207825bf775dcc9a95d1c50c9d12..4d516a2b3fa81a482ebaf5337efd7c080871bd07 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-data-model.md +++ b/zh-cn/application-dev/ui/ui-ts-building-data-model.md @@ -13,7 +13,7 @@ 2. 定义食物数据的存储模型FoodData和枚举变量Category,FoodData类包含食物id、名称(name)、分类(category)、图片(image)、热量(calories)、蛋白质(protein)、脂肪(fat)、碳水(carbohydrates)和维生素C(vitaminC)属性。 ArkTS语言是在ts语言的基础上的扩展,同样支持ts语法。 - ``` + ```ts enum Category { Fruit, Vegetable, @@ -52,7 +52,7 @@ 4. 创建食物资源数据。在model文件夹下创建FoodDataModels.ets,在该页面中声明食物成分数组FoodComposition。以下示例创建了两个食物数据。 - ``` + ```ts const FoodComposition: any[] = [ { 'name': 'Tomato', 'image': $r('app.media.Tomato'), 'category': Category.Vegetable, 'calories': 17, 'protein': 0.9, 'fat': 0.2, 'carbohydrates': 3.9, 'vitaminC': 17.8 }, { 'name': 'Walnut', 'image': $r('app.media.Walnut'), 'category': Category.Nut, 'calories': 654 , 'protein': 15, 'fat': 65, 'carbohydrates': 14, 'vitaminC': 1.3 } @@ -62,7 +62,7 @@ 实际开发中,开发者可以自定义更多的数据资源,当食物资源很多时,建议使用数据懒加载LazyForEach。 5. 创建initializeOnStartUp方法来初始化FoodData的数组。在FoodDataModels.ets中使用了定义在FoodData.ets的FoodData和Category,所以要将FoodData.ets的FoodData类export,在FoodDataModels.ets内import FoodData和Category。 - ``` + ```ts // FoodData.ets export enum Category { ...... diff --git a/zh-cn/application-dev/ui/ui-ts-components-web.md b/zh-cn/application-dev/ui/ui-ts-components-web.md index 6a72cc647601e6f072b59a61b58805df0d16c0b8..6f4acc31caca52b4bab2e97e9913922dd86904fa 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-web.md +++ b/zh-cn/application-dev/ui/ui-ts-components-web.md @@ -198,6 +198,6 @@ struct WebComponent { 针对Web开发,有以下相关实例可供参考: -- [`Web`:Web(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Web) +- [`Web`:Web(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Web) -- [Web组件加载本地H5小程序(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent) \ No newline at end of file +- [Web组件加载本地H5小程序(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent) \ 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 deleted file mode 100644 index 45d22d02d3255dddcd90760c911595a942c2ee17..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-components.md +++ /dev/null @@ -1,78 +0,0 @@ -# 初识Component - -在自定义组件之前,需要先了解什么是[组件和装饰器](#组件和装饰器),并进行初始化组件。然后通过[修改组件属性和构造参数](#修改组件属性和构造参数),实现一个自定义组件。 - - -## 组件和装饰器 - -在声明式UI中,所有的页面都是由组件构成。组件的数据结构为struct,装饰器[@Component](../ui/ts-component-based-component.md)是组件化的标志。用@Component修饰的struct表示这个结构体有了组件化的能力。 - -自定义组件的声明方式为: - -```ts -@Component -struct MyComponent {} -``` - -在IDE创建工程模板中,MyComponent就是一个可以居中显示文字的自定义组件。开发者可以在Component的build方法里描述自己的UI结构,但需要遵循Builder的接口约束。 - -```ts -interface Builder { - build: () => void -} -``` - -[@Entry](../ui/ts-component-based-entry.md)修饰的Component表示该Component是页面的总入口,也可以理解为页面的根节点。值得注意的是,一个页面有且仅能有一个@Entry,只有被@Entry修饰的组件或者其子组件,才会在页面上显示。 - -@Component和@Entry都是基础且十分重要的装饰器。简单地理解,装饰器就是某一种修饰,给被装饰的对象赋予某一种能力,比如@Entry就是页面入口的能力,@Component就是组件化能力。 - -在了解了组件和装饰器这两个重要概念后,接下来可以开始开发健康饮食应用。 - - -## 修改组件属性和构造参数 - -开发者创建系统组件时,会显示其默认样式。开发者可以通过更改组件的属性样式来改变组件的视图显示。 - -1. 修改Text组件的fontSize属性来更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: - 1. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 - 2. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 - 3. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 - - 属性方法要紧随组件,通过“.”运算符连接,也可以通过链式调用的方式配置组件的多个属性。 - - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168728272](figures/zh-cn_image_0000001168728272.png) - -2. 修改Text组件的显示内容“Hello World”为“Tomato”,通过修改Text组件的构造参数来实现。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .width('100%') - .height('100%') - } - } - ``` - - ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-project.md b/zh-cn/application-dev/ui/ui-ts-creating-project.md deleted file mode 100644 index e35ca9fa9b76d6dd69cbdc26864d649971265693..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/ui/ui-ts-creating-project.md +++ /dev/null @@ -1,65 +0,0 @@ -# 创建声明式UI工程 - - - -创建工程之前,首先需要安装DevEco Studio。 - - -1. 打开DevEco Studio,点击Create Project。如果已有一个工程,则点击File > New > New project。 - - ![zh-cn_image_0000001168956332](figures/zh-cn_image_0000001168956332.png) - -2. - 进入选择Ability Template界面,选择Empty Ability。 - - ![zh-cn_image_0000001168059158](figures/zh-cn_image_0000001168059158.png) - -3. 进入配置工程界面,将工程名字改为HealthyDiet,Project Type选择Application,Compile API选择8,UI Syntax选择eTS。DevEco Studio会默认将工程保存在C盘,如果要更改工程保存位置,点击Save Location的文件夹图标,自行指定工程创建位置。配置完成后点击Finish。 - - - ![zh-cn_image_0000001167746622](figures/zh-cn_image_0000001167746622.png) - -4. 工程创建完成后,打开app.ets。 - app.ets提供了应用生命周期的接口:onCreate和onDestroy,分别在应用创建之初和应用被销毁时调用。在app.ets里可以声明全局变量,并且声明的数据和方法是整个应用共享的。 - - ``` - export default { - onCreate() { - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } - ``` - -5. 在工程导航栏里,打开index.ets。该页面展示了当前的UI描述,声明式UI框架会自动生成一个组件化的struct,这个struct遵循Builder接口声明,在build方法里面声明当前的布局和组件。 - ``` - @Entry - @Component - struct MyComponent { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - .height('100%') - } - } - ``` - -6. 点击右侧的Previewer按钮,打开预览窗口。可以看到预览窗口中“Hello World”居中加粗显示。 - 如果没有Previewer按钮,点击settings > SDK Manager > OpenHarmony SDK> Tools 查看是否安装了Previewer。 - - ![zh-cn_image_0000001214595111](figures/zh-cn_image_0000001214595111.png) - -7. 应用安装到设备上运行应用。 - - 将设备连接电脑,等IDE识别到物理设备后,点击Run 'entry'按钮。 - ![zh-cn_image_0000001148858818](figures/zh-cn_image_0000001148858818.png) - - 在安装之前,需要配置应用签名。安装成功后,点击屏幕上的Run图标打开应用,可以看到居中加粗显示的“Hello World”。 - - ![zh-cn_image_0000001158896538](figures/zh-cn_image_0000001158896538.png) diff --git a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md index 18152fe84e1c3ff337bd9db0b41ce9c3359adcfa..ca4fe0bd1e5f2f04a8e2aba9d881f0a37f3ac969 100644 --- a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md +++ b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md @@ -2,12 +2,16 @@ 在这一小节中,我们将开始食物详情页的开发,学习如何通过容器组件Stack、Flex和基础组件Image、Text,构建用户自定义组件,完成图文并茂的食物介绍。 +在创建页面前,请先创建eTS工程,FA模型请参考[创建FA模型的eTS工程](../quick-start/start-with-ets-stage.md#创建ets工程),Stage模型请参考[创建Stage模型的eTS工程](..//quick-start/start-with-ets-fa.md#创建ets工程)。 + ## 构建Stack布局 1. 创建食物名称。 - 删掉工程模板的build方法的代码,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 - ``` + + 在index.ets文件中,创建Stack组件,将Text组件放进Stack组件的花括号中,使其成为Stack组件的子组件。Stack组件为堆叠组件,可以包含一个或多个子组件,其特点是后一个子组件覆盖前一个子组件。 + + ```ts @Entry @Component struct MyComponent { @@ -22,11 +26,11 @@ ``` ![zh-cn_image_0000001214128687](figures/zh-cn_image_0000001214128687.png) - + 2. 食物图片展示。 创建Image组件,指定Image组件的url,Image组件是必选构造参数组件。为了让Text组件在Image组件上方显示,所以要先声明Image组件。图片资源放在resources下的rawfile文件夹内,引用rawfile下资源时使用`$rawfile('filename')`的形式,filename为rawfile目录下的文件相对路径。当前`$rawfile`仅支持Image控件引用图片资源。 - - ``` + + ```ts @Entry @Component struct MyComponent { @@ -42,30 +46,29 @@ ``` -![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) + ![zh-cn_image_0000001168410342](figures/zh-cn_image_0000001168410342.png) 3. 通过资源访问图片。 除指定图片路径外,也可以使用引用媒体资源符$r引用资源,需要遵循resources文件夹的资源限定词的规则。右键resources文件夹,点击New>Resource Directory,选择Resource Type为Media(图片资源)。 将Tomato.png放入media文件夹内。就可以通过`$r('app.type.name')`的形式引用应用资源,即`$r('app.media.Tomato')`。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` 4. 设置Image宽高,并且将image的objectFit属性设置为ImageFit.Contain,即保持图片长宽比的情况下,使得图片完整地显示在边界内。 如果Image填满了整个屏幕,原因如下: @@ -73,83 +76,53 @@ 2. Image的objectFit默认属性是ImageFit.Cover,即在保持长宽比的情况下放大或缩小,使其填满整个显示边界。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack() { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - + ``` - ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) + ![zh-cn_image_0000001214210217](figures/zh-cn_image_0000001214210217.png) 5. 设置食物图片和名称布局。设置Stack的对齐方式为底部起始端对齐,Stack默认为居中对齐。设置Stack构造参数alignContent为Alignment.BottomStart。其中Alignment和FontWeight一样,都是框架提供的内置枚举类型。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) + Image($r('app.media.Tomato')) + .objectFit(ImageFit.Contain) + .height(357) + Text('Tomato') + .fontSize(26) + .fontWeight(500) } } } -``` - - - ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - -6. 通过设置Stack的背景颜色来改变食物图片的背景颜色,设置颜色有四种方式: - 1. 通过框架提供的Color内置枚举值来设置,比如backgroundColor(Color.Red),即设置背景颜色为红色。 - 2. string类型参数,支持的颜色格式有:rgb、rgba和HEX颜色码。比如backgroundColor('\#0000FF'),即设置背景颜色为蓝色,backgroundColor('rgb(255, 255, 255)'),即设置背景颜色为白色。 - 3. number类型参数,支持十六进制颜色值。比如backgroundColor(0xFF0000),即设置背景颜色为红色。 - - 4. Resource类型参数请参考[资源访问](ts-resource-access.md) 。 - - -``` -@Entry - @Component - struct MyComponent { - build() { - Stack({ alignContent: Alignment.BottomStart }) { - Image($r('app.media.Tomato')) - .objectFit(ImageFit.Contain) - .height(357) - Text('Tomato') - .fontSize(26) - .fontWeight(500) - } - .backgroundColor('#FFedf2f5') - } -} -``` + ``` + ![zh-cn_image_0000001168728872](figures/zh-cn_image_0000001168728872.png) - ![zh-cn_image_0000001168888822](figures/zh-cn_image_0000001168888822.png) +6. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: -7. 调整Text组件的外边距margin,使其距离左侧和底部有一定的距离。margin是简写属性,可以统一指定四个边的外边距,也可以分别指定。具体设置方式如下: 1. 参数为Length时,即统一指定四个边的外边距,比如margin(20),即上、右、下、左四个边的外边距都是20。 2. 参数为{top?: Length, right?: Length, bottom?: Length, left?:Length},即分别指定四个边的边距,比如margin({ left: 26, bottom: 17.4 }),即左边距为26,下边距为17.4。 -``` -@Entry + ```ts + @Entry @Component struct MyComponent { build() { @@ -161,20 +134,19 @@ .fontSize(26) .fontWeight(500) .margin({left: 26, bottom: 17.4}) - } - .backgroundColor('#FFedf2f5') + } } } -``` + ``` + ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) - ![zh-cn_image_0000001213968747](figures/zh-cn_image_0000001213968747.png) +7. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 -8. 调整组件间的结构,语义化组件名称。创建页面入口组件为FoodDetail,在FoodDetail中创建Column,设置水平方向上居中对齐 alignItems(HorizontalAlign.Center)。MyComponent组件名改为FoodImageDisplay,为FoodDetail的子组件。 Column是子组件竖直排列的容器组件,本质为线性布局,所以只能设置交叉轴方向的对齐。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -185,11 +157,10 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .height(357) - .backgroundColor('#FFedf2f5') + .height(357) } } - + @Entry @Component struct FoodDetail { @@ -200,9 +171,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - - + ``` ## 构建Flex布局 @@ -210,8 +179,8 @@ 1. 创建ContentTable组件,使其成为页面入口组件FoodDetail的子组件。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -223,15 +192,15 @@ .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) } - .backgroundColor('#FFedf2f5') } } - + @Component struct ContentTable { - build() {} + build() { + } } - + @Entry @Component struct FoodDetail { @@ -243,8 +212,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 2. 创建Flex组件展示Tomato两类成分。 一类是热量Calories,包含卡路里(Calories);一类是营养成分Nutrition,包含蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)。 @@ -253,8 +221,8 @@ 已省略FoodImageDisplay代码,只针对ContentTable进行扩展。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex() { @@ -270,7 +238,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -282,15 +250,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) - + ``` + + + ![zh-cn_image_0000001169759552](figures/zh-cn_image_0000001169759552.png) + 3. 调整布局,设置各部分占比。分类名占比(layoutWeight)为1,成分名和成分含量一共占比(layoutWeight)2。成分名和成分含量位于同一个Flex中,成分名占据所有剩余空间flexGrow(1)。 -``` -@Component + ```ts + @Component struct FoodImageDisplay { build() { Stack({ alignContent: Alignment.BottomStart }) { @@ -301,11 +269,10 @@ .fontSize(26) .fontWeight(500) .margin({ left: 26, bottom: 17.4 }) - } - .backgroundColor('#FFedf2f5') + } } } - + @Component struct ContentTable { build() { @@ -327,7 +294,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -339,16 +306,15 @@ .alignItems(HorizontalAlign.Center) } } -``` - - - ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) - + ``` + + ![zh-cn_image_0000001215079443](figures/zh-cn_image_0000001215079443.png) + 4. 仿照热量分类创建营养成分分类。营养成分部分(Nutrition)包含:蛋白质(Protein)、脂肪(Fat)、碳水化合物(Carbohydrates)和维生素C(VitaminC)四个成分,后三个成分在表格中省略分类名,用空格代替。 设置外层Flex为竖直排列FlexDirection.Column, 在主轴方向(竖直方向)上等距排列FlexAlign.SpaceBetween,在交叉轴方向(水平轴方向)上首部对齐排列ItemAlign.Start。 -``` -@Component + ```ts + @Component struct ContentTable { build() { Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { @@ -427,7 +393,7 @@ .padding({ top: 30, right: 30, left: 30 }) } } - + @Entry @Component struct FoodDetail { @@ -439,8 +405,7 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` 5. 使用自定义构造函数\@Builder简化代码。可以发现,每个成分表中的成分单元其实都是一样的UI结构。 ![zh-cn_image_0000001169599582](figures/zh-cn_image_0000001169599582.png) @@ -449,8 +414,8 @@ 在ContentTable内声明\@Builder修饰的IngredientItem方法,用于声明分类名、成分名称和成分含量UI描述。 -``` - @Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -469,13 +434,12 @@ } } } -``` - + ``` - 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 + 在ContentTable的build方法内调用IngredientItem接口,需要用this去调用该Component作用域内的方法,以此来区分全局的方法调用。 -``` -@Component + ```ts + @Component struct ContentTable { ...... build() { @@ -490,13 +454,12 @@ .padding({ top: 30, right: 30, left: 30 }) } } -``` - + ``` - ContentTable组件整体代码如下。 + ContentTable组件整体代码如下。 -``` -@Component + ```ts + @Component struct ContentTable { @Builder IngredientItem(title:string, name: string, value: string) { Flex() { @@ -514,21 +477,20 @@ .layoutWeight(2) } } - - build() { - Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { - this.IngredientItem('Calories', 'Calories', '17kcal') - this.IngredientItem('Nutrition', 'Protein', '0.9g') - this.IngredientItem('', 'Fat', '0.2g') - this.IngredientItem('', 'Carbohydrates', '3.9g') - this.IngredientItem('', 'VitaminC', '17.8mg') - } - .height(280) - .padding({ top: 30, right: 30, left: 30 }) - } - + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', 'Calories', '17kcal') + this.IngredientItem('Nutrition', 'Protein', '0.9g') + this.IngredientItem('', 'Fat', '0.2g') + this.IngredientItem('', 'Carbohydrates', '3.9g') + this.IngredientItem('', 'VitaminC', '17.8mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } } - + @Entry @Component struct FoodDetail { @@ -540,10 +502,9 @@ .alignItems(HorizontalAlign.Center) } } -``` - + ``` - ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) + ![zh-cn_image_0000001215199399](figures/zh-cn_image_0000001215199399.png) 通过学习Stack布局和Flex布局已完成食物的图文展示和营养成分表,构建出第一个普通视图的食物详情页。在下一个章节中,将开发食物分类列表页,并完成食物分类列表页面和食物详情页面的跳转和数据传递,现在我们就进入下一个章节的学习吧。 diff --git a/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..970076fbc3bdb74596a565cf1090f9765d01d4bf --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-custom-component-lifecycle-callbacks.md @@ -0,0 +1,139 @@ +# 自定义组件的生命周期 + +自定义组件的生命周期回调函数用于通知用户该自定义组件的生命周期,这些回调函数是私有的,在运行时由开发框架在特定的时间进行调用,不能从应用程序中手动调用这些回调函数。 + +> **说明:** +> +> - 允许在生命周期函数中使用Promise和异步回调函数,比如网络资源获取,定时器设置等; +> +> - 不允许在生命周期函数中使用async await。 + + +## aboutToAppear + +aboutToAppear?(): void + +aboutToAppear函数在创建自定义组件的新实例后,在执行其build函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build函数中生效。 + +## aboutToDisappear + +aboutToDisappear?(): void + +aboutToDisappear函数在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。 + +**示例1:** + +```ts +// xxx.ets +@Entry +@Component +struct CountDownTimerComponent { + @State countDownFrom: number = 10 + private timerId: number = -1 + + aboutToAppear(): void { + this.timerId = setInterval(() => { + if (this.countDownFrom <= 1) { + clearTimeout(this.timerId) // countDownFrom小于等于1时清除计时器 + } + this.countDownFrom -= 1 + }, 1000) // countDownFrom每1s减1 + } + + aboutToDisappear(): void { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } + + build() { + Column() { + Text(`${this.countDownFrom} sec left`) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![aboutToAppear](figures/aboutToAppear.gif) + +上述示例表明,生命周期函数对于允许CountDownTimerComponent管理其计时器资源至关重要,类似的函数也包括异步从网络请求加载资源。 + +## onPageShow + +onPageShow?(): void + +页面每次显示时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onPageHide + +onPageHide?(): void + +页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry修饰的自定义组件生效。 + +## onBackPress + +onBackPress?(): void + +当用户点击返回按钮时触发,仅@Entry修饰的自定义组件生效。返回true表示页面自己处理返回逻辑,不进行页面路由,返回false表示使用默认的路由返回逻辑。不设置返回值按照false处理。 + +**示例2:** + +```ts +// xxx.ets +@Entry +@Component +struct IndexComponent { + @State textColor: Color = Color.Black + + onPageShow() { + this.textColor = Color.Blue + console.info('IndexComponent onPageShow') + } + + onPageHide() { + this.textColor = Color.Transparent + console.info('IndexComponent onPageHide') + } + + onBackPress() { + this.textColor = Color.Red + console.info('IndexComponent onBackPress') + } + + build() { + Column() { + Text('Hello World') + .fontColor(this.textColor) + .fontSize(30) + .margin(30) + }.width('100%') + } +} +``` + +![lifecycle](figures/lifecycle.PNG) + +## onLayout + +onLayout?(children: Array, constraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)): void + +框架会在自定义组件布局时,将该自定义组件的子节点信息和自身的尺寸范围通过onLayout传递给该自定义组件。不允许在onLayout函数中改变状态变量。 + +## onMeasure + +onMeasure?(children: Array, constraint: [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions)): void + +框架会在自定义组件确定尺寸时,将该自定义组件的子节点信息和自身的尺寸范围通过onMeasure传递给该自定义组件。不允许在onMeasure函数中改变状态变量。 + +## LayoutChild类型说明 + +| 参数 | 参数类型 | 描述 | +| ----- | ----------- | ----------- | +| name | string | 子组件名称 | +| id | string | 子组件id | +| constraint | [ConstraintSizeOptions](../reference/arkui-ts/ts-types.md#constraintsizeoptions) | 子组件约束尺寸 | +| borderInfo | { borderWidth: number, margin: [Margin](../reference/arkui-ts/ts-types.md#margin), padding: [Padding](../reference/arkui-ts/ts-types.md#padding) } | 子组件边框样式 | +| position | { x: number, y: number } | 子组件位置坐标 | diff --git a/zh-cn/application-dev/ui/ui-ts-developing-intro.md b/zh-cn/application-dev/ui/ui-ts-developing-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..b0d3945197bc79f66ddc57b373271b74d03ff4e8 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-developing-intro.md @@ -0,0 +1,227 @@ +# 声明式开发指导 + +## 开发说明 + +声明式UI的工程结构还请参考[OpenHarmony APP工程结构介绍](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section133380945818)。其中,.ets结尾的ArkTS文件用于描述UI布局、样式、事件交互和页面逻辑,支持导入TypeScript和JavaScript文件。资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源分类与访问](../quick-start/resource-categories-and-access.md)。 + +在开发页面之前,请先[学习ArkTS语言](../quick-start/arkts-get-started.md)了解声明式UI的基本语法。 + +在开发页面时,可先根据使用场景,在[常见布局](ui-ts-layout-linear.md)中选择合适的布局。再根据页面需要实现的内容,为页面添加系统内置组件,更新组件状态。页面开发过程中请参考[自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md)了解如何添加需要的生命周期回调方法。 + +也可在页面中添加[绘图](../reference/arkui-ts/ts-drawing-components-circle.md)和[动画](../reference/arkui-ts/ts-animatorproperty.md),丰富页面的展现形态。还可以使用[路由](../reference/apis/js-apis-router.md)实现多个页面之间的跳转和数据传递。 + +另外请参考[性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md),避免低性能代码对应用的性能造成负面影响。 + +## 创建页面 + +请先根据页面预期效果选择布局结构创建页面,并在页面中添加基础的系统内置组件。下述示例采用了[弹性布局(Flex)](ui-ts-layout-flex.md),对页面中的Text组件进行横纵向居中布局显示。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello') + } + .width('100%') + .height('100%') + } + } + ``` + +## 修改组件样式 + +创建系统内置组件时,若不设置属性方法,则会显示其默认样式。通过更改组件的属性样式或者组件支持的[通用属性](../reference/arkui-ts/ts-universal-attributes-size.md)样式,设置可以改变组件的UI显示。 + +1. 通过修改Text组件的构造参数,将Text组件的显示内容修改为“Tomato”。 + +2. 修改Text组件的fontSize属性更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: + + a. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 + + b. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 + + c. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 + + 属性方法要紧随组件,通过“.”操作符连接,也可以通过链式调用的方式配置组件的多个属性。 + + ```ts + // xxx.ets + @Entry + @Component + struct MyComponent { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Tomato') + .fontSize(26) + .fontWeight(500) + } + .width('100%') + .height('100%') + } + } + ``` + + ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) + +## 组件成员变量初始化 + +自定义组件的成员变量可以通过[本地初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)和[在构造组件时通过构造参数初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)两种方式实现,具体允许哪种方式取决于该变量所使用的装饰器: + + +**示例:** + +```ts +// xxx.ets +class ClassA { + public str: string + + constructor(str: string) { + this.str = str + } +} + +@Entry +@Component +struct Parent { + // Parent的变量parentState进行本地初始化 + @State parentState: ClassA = new ClassA('hello') + + build() { + Column() { + Row() { + CompA({ aState: new ClassA('Tomato'), aLink: $parentState }) + } + // aState在CompA中已进行初始化,因此可以缺省 + Row() { + CompA({ aLink: $parentState }) + } + }.width('100%') + } +} + +@Component +struct CompA { + // CompA中的变量aState进行本地初始化,aLink在Parent中使用时通过构造参数初始化 + @State aState: any = new ClassA('CompA') + @Link aLink: ClassA + + build() { + Row() { + Text(JSON.stringify(this.aState)).fontSize(20).margin(30) + Text(JSON.stringify(this.aLink)).fontSize(20).margin(30) + } + } +} +``` + +![component](figures/component.PNG) + +## 组件的状态更新 + +组件的状态可以通过动态修改组件成员变量的值来更新,下面以示例来进行说明。 + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct ParentComp { + @State isCountDown: boolean = true + + build() { + Column() { + Text(this.isCountDown ? 'Count Down' : 'Stopwatch').fontSize(20).margin(20) + if (this.isCountDown) { + // 图片资源放在media目录下 + Image($r("app.media.countdown")).width(120).height(120) + TimerComponent({ counter: 10, changePerSec: -1, showInColor: Color.Red }) + } else { + // 图片资源放在media目录下 + Image($r("app.media.stopwatch")).width(120).height(120) + TimerComponent({ counter: 0, changePerSec: +1, showInColor: Color.Black }) + } + Button(this.isCountDown ? 'Switch to Stopwatch' : 'Switch to Count Down') + .onClick(() => { + this.isCountDown = !this.isCountDown + }) + }.width('100%') + } +} + +// 自定义计时器/倒计时组件 +@Component +struct TimerComponent { + @State counter: number = 0 + private changePerSec: number = -1 + private showInColor: Color = Color.Black + private timerId: number = -1 + + build() { + Text(`${this.counter}sec`) + .fontColor(this.showInColor) + .fontSize(20) + .margin(20) + } + + aboutToAppear() { + this.timerId = setInterval(() => { + this.counter += this.changePerSec + }, 1000) + } + + aboutToDisappear() { + if (this.timerId > 0) { + clearTimeout(this.timerId) + this.timerId = -1 + } + } +} +``` + +![component](figures/component.gif) + +**初始创建和渲染:** + +1. 创建父组件ParentComp; + +2. 本地初始化ParentComp的状态变量isCountDown; + +3. 执行ParentComp的build函数; + +4. 创建Column组件; + 1. 创建Text组件,设置其文本展示内容,并将Text组件实例添加到Column中; + 2. 判断if条件,创建true条件下的元素; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数创建TimerComponent; + 1. 创建TimerComponent对象; + 2. 本地初始化成员变量初始值; + 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; + 4. 执行TimerComponent的aboutToAppear函数; + 5. 执行TimerComponent的build函数,创建相应的UI描述结构; + 3. 创建Button内置组件,设置相应的内容。 + +**状态更新:** + +用户单击按钮时: + +1. ParentComp的isCountDown状态变量的值更改为false; + +2. 执行ParentComp的build函数; + +3. Column组件被重用并执行重新初始化; + +4. Column的子组件会重用内存中的对象,但会进行重新初始化; + 1. Text组件会被重用,但使用新的文本内容进行重新初始化; + 2. 判断if条件,使用false条件下的元素; + 1. 原来true条件的组件不再使用,将这些组件销毁; + 1. 销毁Image组件实例; + 2. 销毁TimerComponent组件实例,aboutToDisappear函数被调用; + 2. 创建false条件下的组件; + 1. 创建Image组件,并设置其图片源地址; + 2. 使用给定的构造函数重新创建TimerComponent; + 3. 初始化TimerComponent,并调用aboutToAppear函数和build函数。 + 3. 重用Button组件,使用新的图片源地址。 diff --git a/zh-cn/application-dev/ui/ui-ts-drawing-feature.md b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md new file mode 100644 index 0000000000000000000000000000000000000000..915748a8acec87ff5a2ef16820467d3999e4d432 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-drawing-feature.md @@ -0,0 +1,404 @@ +# 绘制图形 + +绘制能力主要是通过框架提供的绘制组件来支撑,支持svg标准绘制命令。 + +本节主要学习如何使用绘制组件,绘制详情页食物成分标签(基本几何图形)和应用Logo(自定义图形)。 + +## 绘制基本几何图形 + +绘制组件封装了一些常见的基本几何图形,比如矩形Rect、圆形Circle、椭圆形Ellipse等,为开发者省去了路线计算的过程。 + +FoodDetail页面的食物成分表里,给每一项成分名称前都加上一个圆形的图标作为成分标签。 + +1. 创建Circle组件,在每一项含量成分前增加一个圆形图标作为标签。设置Circle的直径为 6vp。修改FoodDetail页面的ContentTable组件里的IngredientItem方法,在成分名称前添加Circle。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + ...... + } + } + ``` + +2. 每个成分的标签颜色不一样,所以我们在build方法中,调用IngredientItem,给每个Circle填充不一样的颜色。 + + ```ts + // FoodDetail.ets + @Component + struct ContentTable { + private foodItem: FoodData + + @Builder IngredientItem(title:string, colorValue: string, name: string, value: string) { + Flex() { + Text(title) + .fontSize(17.4) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Flex({ alignItems: ItemAlign.Center }) { + Circle({width: 6, height: 6}) + .margin({right: 12}) + .fill(colorValue) + Text(name) + .fontSize(17.4) + .flexGrow(1) + Text(value) + .fontSize(17.4) + } + .layoutWeight(2) + } + } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) { + this.IngredientItem('Calories', '#FFf54040', 'Calories', this.foodItem.calories + 'kcal') + this.IngredientItem('Nutrition', '#FFcccccc', 'Protein', this.foodItem.protein + 'g') + this.IngredientItem(' ', '#FFf5d640', 'Fat', this.foodItem.fat + 'g') + this.IngredientItem(' ', '#FF9e9eff', 'Carbohydrates', this.foodItem.carbohydrates + 'g') + this.IngredientItem(' ', '#FF53f540', 'VitaminC', this.foodItem.vitaminC + 'mg') + } + .height(280) + .padding({ top: 30, right: 30, left: 30 }) + } + } + ``` + + ![drawing-feature](figures/drawing-feature.png) + +## 绘制自定义几何图形 + +除绘制基础几何图形,开发者还可以使用Path组件来绘制自定义的路线,下面进行绘制应用的Logo图案。 + +1. 在pages文件夹下创建新的eTS页面Logo.ets。 + + ![drawing-feature1](figures/drawing-feature1.png) + +2. Logo.ets中删掉模板代码,创建Logo Component。 + + ```ts + @Entry + @Component + struct Logo { + build() { + } + } + ``` + +3. 创建Flex组件为根节点,宽高设置为100%,设置其在主轴方向和交叉轴方向的对齐方式都为Center,创建Shape组件为Flex子组件。 + + Shape组件是所有绘制组件的父组件。如果需要组合多个绘制组件成为一个整体,需要创建Shape作为其父组件。 + + 我们要绘制的Logo的大小630px * 630px。声明式UI范式支持多种长度单位的设置,在前面的章节中,我们直接使用number作为参数,即采用了默认长度单位vp,虚拟像素单位。vp和设备分辨率以及屏幕密度有关。比如设备分辨率为1176 * 2400,屏幕基准密度(resolution)为3,vp = px / resolution,则该设备屏幕宽度是392vp。 + + 但是绘制组件采用svg标准,默认采取px为单位的,为方便统一,在这绘制Logo这一部分,统一采取px为单位。声明式UI框架同样也支持px单位,入参类型为string,设置宽度为630px,即210vp,设置方式为width('630px')或者width(210)。 + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + } + } + ``` + +4. 给页面填充渐变色。设置为线性渐变,偏移角度为180deg,三段渐变 #BDE895 -->95DE7F --> #7AB967,其区间分别为[0, 0.1], (0.1, 0.6], (0.6, 1]。 + + ```ts + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + ``` + + ![drawing-feature2](figures/drawing-feature2.png) + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature3](figures/drawing-feature3.png) + +5. 绘制第一条路线Path,设置其绘制命令。 + + ```ts + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + ``` + + Path的绘制命令采用svg标准,上述命令可分解为: + + ```ts + M162 128.7 + ``` + + 将笔触移动到(Moveto)坐标点(162, 128.7)。 + + ```ts + a222 222 0 0 1 100.8 374.4 + ``` + + 画圆弧线(elliptical arc)半径rx,ry为222,x轴旋转角度x-axis-rotation为0,角度大小large-arc-flag为0,即小弧度角,弧线方向(sweep-flag)为1,即逆时针画弧线,小写a为相对位置,即终点坐标为(162 + 100.8 = 262.8, 128.7 + 374.4 = 503.1)。 + + ```ts + H198 + ``` + + 画水平线(horizontal lineto)到198,即画(262.8, 503.1)到(198, 503.1)的水平线。 + + ```ts + a36 36 0 0 3 -36 -36 + ``` + + 画圆弧线(elliptical arc),含义同上,结束点为(198 - 36 = 162, 503.1 - 36 = 467.1)。 + + ```ts + V128.7 + ``` + + 画垂直线(vertical lineto)到128.7,即画(162, 467.1)到(162, 128.7)的垂直线。 + + ```ts + z + ``` + + 关闭路径(closepath)。 + + ![drawing-feature4](figures/drawing-feature4.png) + + 填充颜色为白色。 + + ```ts + .fill(Color.White) + ``` + + ```ts + @Entry + @Component + struct Logo { + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature5](figures/drawing-feature5.png) + +6. 在Shape组件内绘制第二个Path。第二条Path的背景色为渐变色,但是渐变色的填充是其整体的box,所以需要clip将其裁剪,入参为Shape,即按照Shape的形状进行裁剪。 + + ```ts + Path() + .commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z') + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z')) + ``` + + Path的绘制命令比较长,可以将其作为组件的成员变量,通过this调用。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + build() { + ...... + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + ...... + } + } + ``` + + ![drawing-feature6](figures/drawing-feature6.png) + +7. 在Shape组件内绘制第二个Path。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature7](figures/drawing-feature7.png) + + 完成应用Logo的绘制。Shape组合了三个Path组件,通过svg命令绘制出一个艺术的叶子,寓意绿色健康饮食方式。 + +8. 添加应用的标题和slogan。 + + ```ts + @Entry + @Component + struct Logo { + private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Shape() { + Path() + .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') + .fill(Color.White) + + Path() + .commands(this.pathCommands1) + .fill('none') + .linearGradient( + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) + .clip(new Path().commands(this.pathCommands1)) + + Path() + .commands(this.pathCommands2) + .fill('none') + .linearGradient( + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) + .clip(new Path().commands(this.pathCommands2)) + } + .height('630px') + .width('630px') + + Text('Healthy Diet') + .fontSize(26) + .fontColor(Color.White) + .margin({ top:300 }) + + Text('Healthy life comes from a balanced diet') + .fontSize(17) + .fontColor(Color.White) + .margin({ top:4 }) + } + .width('100%') + .height('100%') + .linearGradient( + { + angle: 180, + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) + } + } + ``` + + ![drawing-feature8](figures/drawing-feature8.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-layout-flex.md b/zh-cn/application-dev/ui/ui-ts-layout-flex.md index 16479a4c171c4459bebb61ca67e9ca9058a80c19..3d33681082d1dc1014a17a4a9dae262a7a9e359f 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-flex.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-flex.md @@ -1,351 +1,560 @@ # 弹性布局 +弹性布局(Flex布局)是自适应布局中使用最为灵活的布局。弹性布局提供一种更加有效的方式来对容器中的子组件进行排列、对齐和分配空白空间。弹性布局 -Flex组件用于创建弹性布局,开发者可以通过Flex的接口创建容器组件,进而对容器内的其他元素进行弹性布局,例如:使三个元素在容器内水平居中,垂直等间隔分散。 +- 容器: [Flex组件](../reference/arkui-ts/ts-container-flex.md)作为Flex布局的容器,用于设置布局相关属性。 +- 子组件: Flex组件内的子组件自动成为布局的子组件。 +- 主轴: 水平方向的轴线,子组件默认沿着主轴排列。主轴开始的位置称为主轴起始端,结束位置称为主轴终点端。 +- 交叉轴: 垂直方向的轴线。交叉始的位置称为主轴首部,结束位置称为交叉轴尾部。 -## 创建弹性布局 + ![](figures/flex.png) -接口的调用形式如下: +## 容器组件属性 -`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -通过参数direction定义弹性布局的布局方向,justifyContent定义弹性布局方向上的子组件对齐方式, alignContent定义与布局方向垂直的方向上的子组件对齐方式,wrap定义内容超过一行时是否换行。 - -## 弹性布局方向 +通过Flex组件提供的Flex接口创建弹性布局。如下: -弹性布局有两个方向,子组件放置的方向是主轴,与主轴垂直的方向是交叉轴。通过direction参数设置容器主轴的方向,可选值有: +`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Row }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) +### 弹性布局方向 +参数direction决定主轴的方向,即子组件的排列方向。可选值有: -- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection.Row相反的方向开始排布。 +![](figures/direction.png) - ```ts - Flex({ direction: FlexDirection.RowReverse }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` +- FlexDirection.Row(默认值):主轴为水平方向,子组件从起始端沿着水平方向开始排布。 - ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + ![zh-cn_image_0000001218579606](figures/zh-cn_image_0000001218579606.png) + +- FlexDirection.RowReverse:主轴为水平方向,子组件从终点端沿着FlexDirection. Row相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.RowReverse }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739566](figures/zh-cn_image_0000001218739566.png) - FlexDirection.Column:主轴为垂直方向,子组件从起始端沿着垂直方向开始排布。 - ```ts - Flex({ direction: FlexDirection.Column }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) - -- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection.Column相反的方向开始排布。 - - ```ts - Flex({ direction: FlexDirection.ColumnReverse }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) - - -## 弹性布局换行 - -默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置其他换行方式,可选值有: - -- FlexWrap.NoWrap : 不换行。如果子元素的宽度总和大于父元素的宽度,则子元素会被压缩宽度。 - - ```ts - Flex({ wrap: FlexWrap.NoWrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) - -- FlexWrap.Wrap:换行。 - - ```ts - Flex({ wrap: FlexWrap.Wrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xD2B48C) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) - -- FlexWrap.WrapReverse:换行,且与行排列方向相反。 - - ```ts - Flex({ wrap: FlexWrap.WrapReverse}) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) - - -## 弹性布局对齐方式 - - -### 主轴对齐 - -可以通过justifyContent参数设置在主轴的对齐方式,可选值有: - -- FlexAlign.Start: 元素在主轴方向首端对齐, 第一个元素与行首对齐,同时后续的元素与前一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.Start }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259634](figures/zh-cn_image_0000001218259634.png) - -- FlexAlign.Center: 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 - - ```ts - Flex({ justifyContent: FlexAlign.Center }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579608](figures/zh-cn_image_0000001218579608.png) - -- FlexAlign.End: 元素在主轴方向尾部对齐, 最后一个元素与行尾对齐,其他元素与后一个对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.End }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739568](figures/zh-cn_image_0000001218739568.png) - -- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素与行首对齐,最后一个元素与行尾对齐。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceBetween }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263019461](figures/zh-cn_image_0000001263019461.png) - -- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。 第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceAround }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263339461](figures/zh-cn_image_0000001263339461.png) - -- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局, 相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 - - ```ts - Flex({ justifyContent: FlexAlign.SpaceEvenly }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263139411](figures/zh-cn_image_0000001263139411.png) - - -### 交叉轴对齐 - -可以通过alignItems参数设置在交叉轴的对齐方式,可选值有: + ```ts + Flex({ direction: FlexDirection.Column }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019457](figures/zh-cn_image_0000001263019457.png) + +- FlexDirection.ColumnReverse:主轴为垂直方向,子组件从终点端沿着FlexDirection. Column相反的方向开始排布。 + + ```ts + Flex({ direction: FlexDirection.ColumnReverse }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339459](figures/zh-cn_image_0000001263339459.png) + +### 弹性布局换行 + +默认情况下,子组件在Flex容器中都排在一条线(又称"轴线")上。通过wrap参数设置子组件换行方式。可选值有: + +- FlexWrap. NoWrap(默认值): 不换行。如果子组件的宽度总和大于父元素的宽度,则子组件会被压缩宽度。 + + ```ts + Flex({ wrap: FlexWrap.NoWrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139409](figures/zh-cn_image_0000001263139409.png) + +- FlexWrap. Wrap:换行,每一行子组件按照主轴方向排列。 + + ```ts + Flex({ wrap: FlexWrap.Wrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xD2B48C) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218419614](figures/zh-cn_image_0000001218419614.png) + +- FlexWrap. WrapReverse:换行,每一行子组件按照主轴反方向排列。 + + ```ts + Flex({ wrap: FlexWrap.WrapReverse}) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259399](figures/zh-cn_image_0000001263259399.png) + +### 弹性布局对齐方式 + +#### 主轴对齐 + +通过justifyContent参数设置在主轴方向的对齐方式,存在下面六种情况: + +![](figures/justifyContent.png) + +- FlexAlign.Start(默认值): 子组件在主轴方向起始端对齐, 第一个子组件与父元素边沿对齐,其他元素与前一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Start }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259634](figures/mainStart.png) + +- FlexAlign.Center: 子组件在主轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.Center }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579608](figures/mainCenter.png) + +- FlexAlign.End: 子组件在主轴方向终点端对齐, 最后一个子组件与父元素边沿对齐,其他元素与后一个元素对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.End }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739568](figures/mainEnd.png) + +- FlexAlign.SpaceBetween: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件和最后一个子组件与父元素边沿对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019461](figures/mainSpacebetween.png) + +- FlexAlign.SpaceAround: Flex主轴方向均匀分配弹性元素,相邻子组件之间距离相同。第一个子组件到主轴起始端的距离和最后一个子组件到主轴终点端的距离是相邻元素之间距离的一半。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceAround }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339461](figures/mainSpacearound.png) + +- FlexAlign.SpaceEvenly: Flex主轴方向元素等间距布局,相邻子组件之间的间距、第一个子组件与主轴起始端的间距、最后一个子组件到主轴终点端的间距均相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceEvenly }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139411](figures/mainSpaceevenly.png) + +#### 交叉轴对齐 + +容器和子组件都可以设置交叉轴对齐方式,且子组件设置的对齐方式优先级较高。 + +##### 容器组件设置交叉轴对齐 +可以通过Flex组件的alignItems参数设置子组件在交叉轴的对齐方式,可选值有: - ItemAlign.Auto: 使用Flex容器中默认配置。 - ```ts - Flex({ alignItems: ItemAlign.Auto }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ alignItems: ItemAlign.Auto }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) + ![zh-cn_image_0000001218419616](figures/zh-cn_image_0000001218419616.png) - ItemAlign.Start: 交叉轴方向首部对齐。 - ```ts - Flex({ alignItems: ItemAlign.Start }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) + ```ts + Flex({ alignItems: ItemAlign.Start }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263259401](figures/zh-cn_image_0000001263259401.png) - ItemAlign.Center: 交叉轴方向居中对齐。 - ```ts - Flex({ alignItems: ItemAlign.Center }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) + ```ts + Flex({ alignItems: ItemAlign.Center }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218259636](figures/zh-cn_image_0000001218259636.png) - ItemAlign.End:交叉轴方向底部对齐。 - ```ts - Flex({ alignItems: ItemAlign.End }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) + ```ts + Flex({ alignItems: ItemAlign.End }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218579610](figures/zh-cn_image_0000001218579610.png) - ItemAlign.Stretch:交叉轴方向拉伸填充,在未设置尺寸时,拉伸到容器尺寸。 - ```ts - Flex({ alignItems: ItemAlign.Stretch }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + ```ts + Flex({ alignItems: ItemAlign.Stretch }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001218739570](figures/zh-cn_image_0000001218739570.png) + +- ItemAlign. Baseline:交叉轴方向文本基线对齐。 + + ```ts + Flex({ alignItems: ItemAlign.Baseline }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) + +##### 子组件设置交叉轴对齐 +子组件的alignSelf属性也可以设置子组件在父容器交叉轴的对齐格式,且会覆盖Flex布局容器中alignItems默认配置。如下例所示: -- ItemAlign.Baseline:交叉轴方向文本基线对齐。 +```ts +Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { //容器组件设置子组件居中 + Text('alignSelf Start').width('25%').height(80) + .alignSelf(ItemAlign.Start) + .backgroundColor(0xF5DEB3) + Text('alignSelf Baseline') + .alignSelf(ItemAlign.Baseline) + .width('25%') + .height(80) + .backgroundColor(0xD2B48C) + Text('alignSelf Baseline').width('25%').height(100) + .backgroundColor(0xF5DEB3) + .alignSelf(ItemAlign.Baseline) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xD2B48C) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xF5DEB3) + +}.width('90%').height(220).backgroundColor(0xAFEEEE) +``` +![](figures/alignself.png) + +上例中,Flex容器中alignItems设置交叉轴子组件的对齐方式为居中,子组件自身设置了alignSelf属性的情况,覆盖父组件的alignItem值,表现为alignSelf的定义。 + +#### 内容对齐 + +可以通过alignContent参数设置子组件各行在交叉轴剩余空间内的对齐方式,只在多行的flex布局中生效,可选值有: + +- FlexAlign.Start: 子组件各行与交叉轴起点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Start }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossStart.png](figures/crossStart.png) + +- FlexAlign.Center: 子组件各行在交叉轴方向居中对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Center }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossCenter.png](figures/crossCenter.png) + +- FlexAlign.End: 子组件各行与交叉轴终点对齐。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.End }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossEnd.png](figures/crossEnd.png) + +- FlexAlign.SpaceBetween: 子组件各行与交叉轴两端对齐,各行间垂直间距平均分布。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceBetween }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacebetween.png](figures/crossSpacebetween.png) + +- FlexAlign.SpaceAround: 子组件各行间距相等,是元素首尾行与交叉轴两端距离的两倍。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacearound.png](figures/crossSpacearound.png) + +- FlexAlign.SpaceEvenly: 子组件各行间距,子组件首尾行与交叉轴两端距离都相等。 + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpaceevenly.png](figures/crossSpaceevenly.png) + +### 弹性布局的自适应拉伸 + +在弹性布局父组件尺寸不够大的时候,通过子组件的下面几个属性设置其再父容器的占比,达到自适应布局能力。 +- flexBasis: 设置子组件在父容器主轴方向上的基准尺寸。如果设置了该值,则子项占用的空间为设置的值;如果没设置或者为auto,那子项的空间为width/height的值。 + ```ts - Flex({ alignItems: ItemAlign.Baseline }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) + Flex() { + Text('flexBasis("auto")') + .flexBasis('auto') // 未设置width以及flexBasis值为auto,内容自身宽松 + .height(100) + .backgroundColor(0xF5DEB3) + Text('flexBasis("auto")'+' width("40%")') + .width('40%') + .flexBasis('auto') //设置width以及flexBasis值auto,使用width的值 + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexBasis(100)') // 未设置width以及flexBasis值为100,宽度为100vp + .flexBasis(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexBasis(100)') + .flexBasis(100) + .width(200) // flexBasis值为100,覆盖width的设置值,宽度为100vp + .height(100) + .backgroundColor(0xD2B48C) + }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) ``` + + ![](figures/flexbasis.png) - ![zh-cn_image_0000001263019463](figures/zh-cn_image_0000001263019463.png) - +- flexGrow: 设置父容器的剩余空间分配给此属性所在组件的比例。用于"瓜分"父组件的剩余空间。 -### 内容对齐 - -可以通过alignContent参数设置在换行组件的行在交叉轴剩余空间内的对齐方式,可选值有: - -- FlexAlign.Start: 左对齐。 - -- FlexAlign.Center: 居中对齐。 - -- FlexAlign.End: 右对齐。 - -- FlexAlign.SpaceBetween: flex items之间的距离相等,与main start、main end两端对齐。 + ```ts + Flex() { + Text('flexGrow(1)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexGrow(3)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xD2B48C) + + Text('no flexGrow') + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexgrow.png) -- FlexAlign.SpaceAround: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间距离的一半。 +上图中,父容器宽度400vp, 三个子组件原始宽度为100vp,综合300vp,剩余空间100vp根据flexGrow值的占比分配给子组件,未设置flexGrow的子组件不参与“瓜分”。 +第一个元素以及第二个元素以2:3分配剩下的100vp。第一个元素为100vp+100vp*2/5=140vp,第二个元素为100vp+100vp*3/5=160vp。 -- FlexAlign.SpaceEvenly: flex items之间的距离相等,flex items与main start、main end之间的距离等于flex items之间的距离。 +- flexShrink: 当父容器空间不足时,子组件的压缩比例。 + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('flexShrink(3)') + .flexShrink(3) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('no flexShrink') + .width(200) + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexShrink(2)') + .flexShrink(2) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexshrink.png) ## 场景示例 - 可使用弹性布局做出子元素排列方式为水平方向排列,且子元素的总宽度超出父元素的宽度不换行,子元素在水平方向两端对齐,中间间距由除首尾外的子元素平分,竖直方向上子元素居中的效果。 +使用弹性布局,可以实现子组件沿水平方向排列,两端对齐,子组件间距平分,竖直方向上子组件居中的效果。示例如下: ```ts -@Entry +@Entry @Component struct FlexExample { build() { @@ -358,7 +567,6 @@ struct FlexExample { } .height(70) .width('90%') - .padding(10) .backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) }.width('100%') @@ -366,9 +574,7 @@ struct FlexExample { } ``` - -![zh-cn_image_0000001261605867](figures/zh-cn_image_0000001261605867.png) - +![zh-cn_image_0000001261605867](figures/flexExample.png) ## 相关实例 diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md new file mode 100644 index 0000000000000000000000000000000000000000..c7346b6212432a1fec21def1f4bd81e719248568 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -0,0 +1,391 @@ +# 栅格布局 + +栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md) +相对于[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)提供了更灵活、更全面的栅格系统实现方案。GridRow为栅格容器组件,只与栅格子组件GridCol在栅格布局场景中使用。 + + +## 栅格容器GridRow + + +栅格容器有columns、gutter、direction、breakpoints四个属性。 +- columns: 栅格布局的主要定位工具,设置栅格布局的总列数。 +- gutter: 设置元素之间的距离,决定内容间的紧密程度。 +- direction: 设置栅格子组件在栅格容器中的排列方向。 +- breakpoints:以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者可根据需要在不同的区间下实现不同的页面布局效果。 + + +首先通过设置断点,得到一系列断点区间;然后,借助栅格组件能力监听应用窗口大小的变化,判断应用当前处于哪个断点区间,最后调整应用的布局。 + +### 栅格系统断点 + +断点以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者根据需求在不同的区间实现不同的页面布局效果。 +[栅格系统默认断点](ui-ts-layout-grid-container.md#系统栅格断点)将设备宽度分为xs、sm、md、lg四类,尺寸范围如下: + +| 断点名称 | 取值范围(vp)| +| --------| ------ | +| xs | [0, 320) | +| sm | [320, 520) | +| md | [520, 840) | +| lg | [840, +∞) | + +在GridRow新栅格组件中,允许开发者使用breakpoints自定义修改断点的取值范围,最多支持6个断点,除了默认的四个断点外, +还可以启用xl,xxl两个断点,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的布局设置。 + +| 断点名称 | 设备描述 | +| ----- | ---------------------------------------- | +| xs | 最小宽度类型设备。 | +| sm | 小宽度类型设备。 | +| md | 中等宽度类型设备。 | +| lg | 大宽度类型设备。 | +| xl | 特大宽度类型设备。 | +| xxl | 超大宽度类型设备。 | + +- 针对断点位置,开发者根据实际使用场景,通过一个单调递增数组设置。由于breakpoints最多支持六个断点,单调递增数组长度最大为5。 + + ```ts + breakpoints: {value: ["100vp", "200vp"]} + ``` + + 表示启用xs、sm、md共3个断点,小于100vp为xs,100vp-200vp为sm,大于200vp为md。 + + ```ts + breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]} + ``` + + 表示启用xs、sm、md、lg、xl共5个断点,小于320vp为xs,320vp-520vp为sm,520vp-840vp为md,840vp-1080vp为lg,大于1080vp为xl。 + + +- 栅格系统通过监听窗口或容器的尺寸变化进行断点,通过reference设置断点切换参考物。 考虑到应用可能以非全屏窗口的形式显示,以应用窗口宽度为参照物更为通用。 + +下例中,使用栅格的默认列数12列,通过断点设置将应用宽度分成六个区间,在各区间中,每个栅格子元素占用的列数均不同。效果如图: + ```ts +GridRow({ + breakpoints: { + value: ['200vp', '300vp', '400vp', '500vp', '600vp'], + reference: BreakpointsReference.WindowSize + } +}) { + ForEach(this.bgColors, (color, index) => { + GridCol({ + span: { + xs: 2, + sm: 3, + md: 4, + lg: 6, + xl: 8, + xxl: 12 + } + }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + }.backgroundColor(color) + }) +} +``` + +![](figures/breakpoints.gif) + + + +### 栅格布局的总列数 + +GridRow中通过columns设置栅格布局的总列数。 + +- columns默认值为12,当未设置columns时,在任何断点下,栅格布局被分成12列。 + ```ts + GridRow() { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + + ![](figures/columns1.png) + +- 当columns类型为number时,栅格布局在任何尺寸设备下都被分为columns列。下面分别设置栅格布局列数为4和8,子元素默认占一列,效果如下: + + ```ts + Row() { + GridRow({ columns: 4 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + + Row() { + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + .width("100%").height("100%") + .onBreakpointChange((breakpoint) => { + this.currentBp = breakpoint + }) + } + .height(160) + .border({ color: Color.Blue, width: 2 }) + .width('90%') + ``` + + ![](figures/columns2.png) + + +- 当columns类型为GridRowColumnOption时,支持下面六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的总列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) { + ForEach(this.bgColors, (item, index) => { + GridCol() { + Row() { + Text(`${index + 1}`) + }.width("100%").height("50") + }.backgroundColor(item) + }) + } + ``` + ![](figures/columns3.gif) + + 如上,若只设置sm, md的栅格总列数,则较小的尺寸使用默认columns值12,较大的尺寸使用前一个尺寸的columns。这里只设置sm:8, md:10,则较小尺寸的xs:12,较大尺寸的参照md的设置,lg:10, xl:10, xxl:10。 + +### 栅格子组件间距 + +GridRow中通过gutter设置子元素在水平和垂直方向的间距。 + +- 当gutter类型为number时,同时设置栅格子组件间水平和垂直方向边距且相等。下例中,设置子组件水平与垂直方向距离相邻元素的间距为10。 + + ```ts + GridRow({ gutter: 10 }){} + ``` + + ![](figures/gutter1.png) + + + +- 当gutter类型为GutterOption时,单独设置栅格子组件水平垂直边距,x属性为水平方向间距,y为垂直方向间距。 + + ```ts + GridRow({ gutter: { x: 20, y: 50 } }){} + ``` + + ![](figures/gutter2.png) + + + +### 排列方向 + +通过GridRow的direction属性设置栅格子组件在栅格容器中的排列方向。 + +- 子组件默认从左往右排列。 + + ```ts + GridRow({ direction: GridRowDirection.Row }){} + ``` + ![](figures/direction1.png) + +- 子组件从右往左排列。 + + ```ts + GridRow({ direction: GridRowDirection.RowReverse }){} + ``` + + ![](figures/direction2.png) + + + +## 栅格子组件GridCol + +GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设置属性两种方式,设置span,offset,order的值。 + +- span的设置 + + ```ts + GridCol({ span: 2 }){} + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.span(2) + GridCol(){}.span({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- offset的设置 + + ```ts + GridCol({ offset: 2 }){} + GridCol({ offset: { xs: 2, sm: 2, md: 2, lg: 2 } }){} + GridCol(){}.offset(2) + GridCol(){}.offset({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + +- order的设置 + + ```ts + GridCol({ order: 2 }){} + GridCol({ order: { xs: 1, sm: 2, md: 3, lg: 4 } }){} + GridCol(){}.order(2) + GridCol(){}.order({ xs: 1, sm: 2, md: 3, lg: 4 }) + ``` + + 下面使用传参的方式演示各属性的使用。 + +### span + +子组件占栅格布局的列数,决定了子组件的宽度,默认为1。 + +- 当类型为number时,子组件在所有尺寸设备下占用的列数相同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: 2 }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span1.png) + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow({ columns: 8 }) { + ForEach(this.bgColors, (color, index) => { + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text(${index}) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/span2.gif) + +### offset + +栅格子组件相对于前一个子组件的偏移列数,默认为0。 +- 当类型为number时,子组件偏移相同列数。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: 2 }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset1.png) + + 栅格默认分成12列,每一个子组件默认占1列,偏移2列,每个子组件及间距共占3列,一行放四个子组件。 + + +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件所占列数设置,各个尺寸下数值可不同。 + + ```ts + GridRow() { + ForEach(this.bgColors, (color, index) => { + GridCol({ offset: { xs: 1, sm: 2, md: 3, lg: 4 } }) { + Row() { + Text("" + index) + }.width("100%").height("50vp") + } + .backgroundColor(color) + }) + } + ``` + + ![](figures/offset2.gif) + +### order + + 栅格子组件的序号,决定子组件排列次序。当子组件不设置order或者设置相同的order, 子组件按照代码顺序展示。当子组件设置不同的order时,order较大的组件在前,较小的在后。 + 当子组件部分设置order,部分不设置order时,未设置order的子组件依次排序靠前,设置了order的子组件按照数值从大到小排列。 + + +- 当类型为number时,子组件在任何尺寸下排序次序一致。 + + ```ts + GridRow() { + GridCol({ order: 5 }) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: 4 }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: 3 }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: 2 }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order1.png) +- 当类型为GridColColumnOption时,支持六种不同尺寸(xs, sm, md, lg, xl, xxl)设备中子组件排序次序设置。 + + ```ts + GridRow() { + GridCol({ order: { xs:1, sm:5, md:3, lg:7}}) { + Row() { + Text("1") + }.width("100%").height("50vp") + }.backgroundColor(Color.Red) + GridCol({ order: { xs:2, sm:2, md:6, lg:1} }) { + Row() { + Text("2") + }.width("100%").height("50vp") + }.backgroundColor(Color.Orange) + GridCol({ order: { xs:3, sm:3, md:1, lg:6} }) { + Row() { + Text("3") + }.width("100%").height("50vp") + }.backgroundColor(Color.Yellow) + GridCol({ order: { xs:4, sm:4, md:2, lg:5} }) { + Row() { + Text("4") + }.width("100%").height("50vp") + }.backgroundColor(Color.Green) + } + ``` + + ![](figures/order2.gif) + + diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md index dc0945724c0725d20d1be7da73790dd602fe71ca..420e594c188eead7944041bd6bffdde13e79c506 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md @@ -1,70 +1,76 @@ # 栅格布局 - 栅格系统作为一种辅助布局的定位工具,在平面设计和网站设计都起到了很好的作用,对移动设备的界面设计有较好的借鉴作用。总结栅格系统对于移动设备的优势主要有: - 1. 给布局提供一种可循的规律,解决多尺寸多设备的动态布局问题。 2. 给系统提供一种统一的定位标注,保证各模块各设备的布局一致性。 3. 给应用提供一种灵活的间距调整方法,满足特殊场景布局调整的可能性。 -为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性useSizeType来实现栅格布局。 +为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性[useSizeType](../reference/arkui-ts/ts-container-grid.md)来实现栅格布局。 ## 栅格系统 栅格系统有Column、Margin、Gutter三个概念。 - -![zh-cn_image_0000001217236574](figures/zh-cn_image_0000001217236574.png) - +![zh-cn_image_0000001224173302](figures/zh-cn_image_0000001224173302.png) 1. Gutter: - 用来控制元素与元素之间距离关系。可以根据设备的不同尺寸,定义不同的gutter值,作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 + 元素之间的距离,决定了内容间的紧密程度。作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。 2. Margin: - 离栅格容器边缘的距离。可以根据设备的不同尺寸,定义不同的margin值,作为栅格布局的统一规范。 + 内容距栅格容器边缘的距离,决定了内容可展示的总宽度。作为栅格布局的统一规范。 3. Column: 栅格布局的主要定位工具。根据设备的不同尺寸,把栅格容器分割成不同的列数,在保证margin和gutter符合规范的情况下,根据总Column的个数计算每个Column列的宽度。 - ### 系统栅格断点 -系统根据不同水平宽度设备对应Column的数量关系,形成了一套断点规则定义。 - -系统以设备的水平宽度的屏幕密度像素值作为断点依据,根据当前设备水平宽度所在的断点范围,定义了设备的宽度类型。系统的栅格断点范围、设备宽度类型及其描述,以及对应的默认总列数(column),边距(margin),间隔(gutter)定义如下: +栅格系统以设备的水平宽度(屏幕密度像素值,vp)作为断点依据,定义设备的宽度类型,设置栅格总列数,间隔,边距,形成了一套断点规则。 +不同设备水平宽度下,栅格系统默认总列数(columns),边距(margin),间隔(gutter)定义如下: | 设备水平宽度断点范围 | 设备宽度类型 | 描述 | columns | gutter | margin | | ----------------------- | ------ | --------- | ------- | ------ | ------ | -| 0<水平宽度<320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | -| 320vp<=水平宽度<600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | -| 600vp<=水平宽度<840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | -| 840<=水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | +| 0< 水平宽度< 320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp | +| 320vp< =水平宽度< 600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp | +| 600vp< =水平宽度< 840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp | +| 840< =水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp | -## 如何使用 +> **说明:** +> +> ArkUI在API9对栅格组件做了重构,推出新的栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md),API9推荐使用新的栅格组件,参考[新栅格组件用法](ui-ts-layout-grid-container-new.md) +> -首先创建栅格容器组件,定义栅格布局,然后给栅格容器内的组件设置不同设备宽度类型下的占用列数。 +## GridContainer栅格组件使用 -### 创建栅格容器 +首先使用栅格容器组件创建栅格布局。 -通过接口`GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})`创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 +### 栅格容器创建与设置 -- 可以通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: +通过接口 `GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})` 创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。 - ```ts - GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} - ``` +通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp: - 栅格容器不设置参数,或者sizeType设置为SizeType.Auto时使用默认的栅格系统定义,如: - ```ts - GridContainer() {} - ``` +```ts +GridContainer({ columns: 6, gutter: 10, margin: 20 }) {} +``` - 上述例子中,默认在小宽度类型设备(SizeType.SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType.MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 +栅格容器不设置参数,或者sizeType设置为SizeType. Auto时使用默认的栅格系统定义,如: -- 也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: +```ts +GridContainer() {} +``` - ```ts +```ts +GridContainer({ sizeType: SizeType.Auto }) +``` + +上述例子中,默认在小宽度类型设备(SizeType. SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType. MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。 + +也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如: + + + +```ts GridContainer({ sizeType: SizeType.SM }) { Row() { Text('1') @@ -78,9 +84,9 @@ } ``` - 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType.SM类型的栅格设置即占用3列,放置在第1列。 + 上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType. SM类型的栅格设置, 即占用3列,放置在第1列。 -### 栅格容器内子组件的栅格设置 +### 子组件的栅格设置 栅格容器中的组件使用通用属性useSizeType设置不同的设备宽度类型的占用列数和列偏移。其中span表示栅格容器组件占据columns的数量;offset表示列偏移量,指将组件放置在哪一个columns上。 如: @@ -97,13 +103,14 @@ GridContainer() { } } ``` -其中`sm: { span: 2, offset: 0 } `指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 + +其中 `sm: { span: 2, offset: 0 } ` 指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。 ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108719.png) ## 场景示例 -使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,而不必书写大量的代码兼容不同宽度类型的设备。 +使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,不必写大量的代码兼容不同宽度类型的设备。 ```ts @Entry @@ -144,11 +151,10 @@ struct GridContainerExample { } ``` - - -小宽度类型设备(SizeType.SM)运行效果: +小宽度类型设备(SizeType. SM)运行效果: ![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108718.png) -中等宽度类型设备(SizeType.MD)运行效果: +中等宽度类型设备(SizeType. MD)运行效果: + ![zh-cn_image_0000001262748569](figures/zh-cn_image_0000001262748569.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid.md b/zh-cn/application-dev/ui/ui-ts-layout-grid.md new file mode 100644 index 0000000000000000000000000000000000000000..69a9fde64de8d9cb79c0cb40c9f6d6eaba8ba757 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid.md @@ -0,0 +1,273 @@ +# 网格布局 + +网格布局(GridLayout)是自适应布局中一种重要的布局,具备较强的页面均分能力,子组件占比控制能力。 +通过[Grid](../reference/arkui-ts/ts-container-grid.md)容器组件和子组件[GridItem](../reference/arkui-ts/ts-container-griditem.md)实现, +Grid用于设置网格布局相关参数,GridItem定义子组件相关特征。优势如下: + +1. 容器组件尺寸发生变化时,所有子组件以及间距等比例调整,实现布局的自适应能力。 +2. 支持自定义网格布局行数和列数,以及每行每列尺寸占比。 +3. 支持设置网格布局中子组件的行列间距。 +4. 支持设置子组件横跨几行或者几列。 + + + +## 容器组件Grid设置 + +### 行列数量占比 +通过Grid的组件的columnsTemplate和rowTemplate属性设置网格布局行列数量与尺寸占比。 + +下面以columnsTemplate为例,介绍该属性的设置,该属性值是一个由多个空格和'数字+fr'间隔拼接的字符串,fr的个数即网格布局的列数,fr前面的数值大小,用于计算该列在网格布局宽度上的占比,最终决定该列的宽度。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四个等分的列,每列宽度相等。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3', '4'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('1fr 2fr 3fr 4fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了四列,每列宽度比值为1:2:3:4。 + +```ts +struct GridExample { + @State Number: Array = ['1', '2', '3'] + + build() { + Column({ space: 5 }) { + Grid() { + ForEach(this.Number, (num: string) => { + GridItem() { + Text(`列${num}`) + .fontSize(16) + .textAlign(TextAlign.Center) + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + }) + } + .columnsTemplate('4fr 2fr 3fr') + .rowsTemplate('1fr') + .columnsGap(10) + .rowsGap(20) + .width('90%') + .backgroundColor(0xF0F0F0) + .height(100) + }.width('100%') + } +} +``` + +定义了三列,每列宽度比值为4:2:3。 + +效果如下: + +![](figures/columnTemplate.png) + +### 排列方式 + +通过layoutDirection可以设置网格布局的主轴方向,决定子组件的排列方式。 +可选值包括Row,RowReverse, Column, ColumnReverse四种情况。 +效果如下: + +![](figures/gridlayout.png) + +### 行列间距 + +columnsGap用于设置网格子组件GridItem垂直方向的间距,rowsGap用于设置GridItem水平方向的间距。 + +```ts +Grid() +.columnsTemplate('1fr 1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +``` + +![](figures/columnGap.png) + +上图中,设置网格布局子组件间的垂直间距为20,水平间距为10。 + +## 网格子组件GridItem设置 + +### 设置子组件占的行列数 + +网格布局的行列标号从1开始,依次编号。 + +子组件横跨多行时,通过rowStart设置子组件起始行编号,rowEnd设置终点行编号。当rowStart值与rowEnd值相同时,子组件只占一个网格。示例如下: + +```ts +Grid() { + GridItem() { + Text('5') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.rowStart(2).rowEnd(3) // 5子组件从第二列到第三列 + + GridItem() { + Text('4') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(4).columnEnd(5) // 4从第四列到第五列 + + GridItem() { + Text('6') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(2).columnEnd(4) // 6从第二列到第四列 + + GridItem() { + Text('9') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) // 从第三列到第四列 +} +.columnsTemplate('1fr 1fr 1fr 1fr 1fr') +.rowsTemplate('1fr 1fr 1fr') +.columnsGap(10) +.rowsGap(20) +.width('90%') +.backgroundColor(0xF0F0F0) +.height('200vp') +.layoutDirection(GridDirection.Column) +``` + +![](figures/griditem.png) + +## 场景示例 + +使用grid布局实现一个计算器的排布效果,代码如下: + +```ts +@Entry +@Component +struct GridExample { + @State Number: Array = ['1', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '0', '.', '/'] + + @Styles textStyle(){ + .backgroundColor(0xd0d0d0) + .width('100%') + .height('100%') + .borderRadius(5) + } + + build() { + Column({ space: 5 }) { + Grid() { + GridItem() { + Text('0') + .fontSize(30) + .textStyle() + }.columnStart(1).columnEnd(4) + + GridItem() { + Text('清空') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + + GridItem() { + Text('回退') + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(3).columnEnd(4) + + ForEach(this.Number, (day: string) => { + if (day === '0') { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + }.columnStart(1).columnEnd(2) + } else { + GridItem() { + Text(day) + .fontSize(16) + .textAlign(TextAlign.Center) + .textStyle() + } + } + }) + } + .columnsTemplate('1fr 1fr 1fr 1fr') + .rowsTemplate('2fr 1fr 1fr 1fr 1fr 1fr') + .columnsGap(10) + .rowsGap(15) + .width('90%') + .backgroundColor(0xF0F0F0) + .height('70%') + }.width('100%').margin({ top: 5 }) + } +} +``` + +在大屏设备上展示效果如下: + +![](figures/gridExp1.png) + +在小屏设备下展示效果如下: + +![](figures/gridExp2.png) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-linear.md b/zh-cn/application-dev/ui/ui-ts-layout-linear.md new file mode 100644 index 0000000000000000000000000000000000000000..0e89b56ad71bb008cae24b6b3151ea7464cd7862 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-linear.md @@ -0,0 +1,370 @@ +# 线性布局 + +线性布局(LinearLayout)是开发中最常用的布局。线性布局的子组件在线性方向上(水平方向和垂直方向)依次排列。 + +通过线性容器[Row](../reference/arkui-ts/ts-container-row.md)和[Column](../reference/arkui-ts/ts-container-column.md)实现线性布局。Column容器内子组件按照垂直方向排列,Row组件中,子组件按照水平方向排列。 + +## 线性布局的排列 + +线性布局的排列方向由所选容器组件决定。根据不同的排列方向,选择使用Row或Column容器创建线性布局,通过调整space,alignItems,justifyContent属性调整子组件的间距,水平垂直方向的对齐方式。 +1. 通过space参数设置主轴(排列方向)上子组件的间距。达到各子组件在排列方向上的等间距效果。 +2. 通过alignItems属性设置子组件在交叉轴(排列方向的垂直方向)的对齐方式。且在各类尺寸屏幕中,表现一致。其中,交叉轴为垂直方向时,取值为[VerticalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#verticalalign),水平方向取值为[HorizontalAlign类型](../reference/arkui-ts/ts-appendix-enums.md#horizontalalign)。 +3. 通过justifyContent属性设置子组件在主轴(排列方向)上的对齐方式。实现布局的自适应均分能力。取值为[FlexAlign类型](../reference/arkui-ts/ts-appendix-enums.md#flexalign)。 + +具体使用以及效果如下表所示: + +|属性名|描述|Row效果图|Column效果图| +|------|---------------------------|----------------------------|---------------------------| +|space |- 横向布局中各子组件的在水平方向的间距
- 纵向布局中个子组件垂直方向间距| ![](figures/rowspace.png) | ![](figures/columnspace.png) | +|alignItems |容器排列方向的垂直方向上,子组件在父容器中的对齐方式|![](figures/rowalign.png) |![](figures/columnalign.png)| +|justifyContent |容器排列方向上,子组件在父容器中的对齐方式 |![](figures/rowjustify.png) |![](figures/columnjustify.png)| + +## 自适应拉伸 + +在线性布局下,常用空白填充组件[Blank](../reference/arkui-ts/ts-basic-components-blank.md),在容器主轴方向自动填充空白空间,达到自适应拉伸效果。 + +```ts +@Entry +@Component +struct BlankExample { + build() { + Column() { + Row() { + Text('Bluetooth').fontSize(18) + Blank() + Toggle({ type: ToggleType.Switch, isOn: true }) + }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }).width('100%') + }.backgroundColor(0xEFEFEF).padding(20).width('100%') + } +} +``` + +![](figures/blank.gif) + +## 自适应缩放 + +自适应缩放是指在各种不同大小设备中,子组件按照预设的比例,尺寸随容器尺寸的变化而变化。在线性布局中有下列方法实现: + +1. 父容器尺寸确定时,设置了layoutWeight属性的子组件与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,在任意尺寸设备下,自适应占满剩余空间。 + + ```ts + @Entry + @Component + struct layoutWeightExample { + build() { + Column() { + Text('1:2:3').width('100%') + Row() { + Column() { + Text('layoutWeight(1)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(4).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(6)') + .textAlign(TextAlign.Center) + }.layoutWeight(6).backgroundColor(0xffd306).height('100%') + + }.backgroundColor(0xffd306).height('30%') + + Text('2:5:3').width('100%') + Row() { + Column() { + Text('layoutWeight(2)') + .textAlign(TextAlign.Center) + }.layoutWeight(2).backgroundColor(0xffd306).height('100%') + + Column() { + Text('layoutWeight(5)') + .textAlign(TextAlign.Center) + }.layoutWeight(5).backgroundColor(0xffed97).height('100%') + + Column() { + Text('layoutWeight(3)') + .textAlign(TextAlign.Center) + }.layoutWeight(3).backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/layoutWeight.gif) + + +3. 父容器尺寸确定时,使用百分比设置子组件以及兄弟组件的width宽度,可以保证各自元素在任意尺寸下的自适应占比。 + + ```ts + @Entry + @Component + struct WidthExample { + build() { + Column() { + Row() { + Column() { + Text('left width 20%') + .textAlign(TextAlign.Center) + }.width('20%').backgroundColor(0xffd306).height('100%') + + Column() { + Text('center width 50%') + .textAlign(TextAlign.Center) + }.width('50%').backgroundColor(0xffed97).height('100%') + + Column() { + Text('right width 30%') + .textAlign(TextAlign.Center) + }.width('30%').backgroundColor(0xffd306).height('100%') + }.backgroundColor(0xffd306).height('30%') + } + } + } + ``` + + ![](figures/width.gif) + + 上例中,在任意大小的设备中,子组件的宽度占比固定。 + +## 定位能力 +- 相对定位 + + 使用组件的[offset属性](../reference/arkui-ts/ts-universal-attributes-location.md)可以实现相对定位,设置元素相对于自身的偏移量。设置该属性,不影响父容器布局,仅在绘制时进行位置调整。使用线性布局和offset可以实现大部分布局的开发。 + + ```ts + @Entry + @Component + struct OffsetExample { + @Styles eleStyle() { + .size({ width: 120, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + } + + build() { + Column({ space: 20 }) { + Row() { + Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('2 offset(15, 30)') + .eleStyle() + .fontSize(16) + .align(Alignment.Start) + .offset({ x: 15, y: 30 }) + Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('4 offset(-10%, 20%)') + .eleStyle() + .fontSize(16) + .offset({ x: '-5%', y: '20%' }) + }.width('90%').height(150).border({ width: 1, style: BorderStyle.Dashed }) + } + .width('100%') + .margin({ top: 25 }) + } + } + ``` + + ![](figures/offset.gif) + + +- 绝对定位 + + 线性布局中可以使用组件的[positon属性](../reference/arkui-ts/ts-universal-attributes-location.md)实现绝对布局(AbsoluteLayout),设置元素左上角相对于父容器左上角偏移位置。对于不同尺寸的设备,使用绝对定位的适应性会比较差,在屏幕的适配上有缺陷。 + + ```ts + @Entry + @Component + struct PositionExample { + @Styles eleStyle(){ + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .size({ width: 120, height: 50 }) + } + + build() { + Column({ space: 20 }) { + // 设置子组件左上角相对于父组件左上角的偏移位置 + Row() { + Text('position(30, 10)') + .eleStyle() + .fontSize(16) + .position({ x: 10, y: 10 }) + + Text('position(50%, 70%)') + .eleStyle() + .fontSize(16) + .position({ x: '50%', y: '70%' }) + + Text('position(10%, 90%)') + .eleStyle() + .fontSize(16) + .position({ x: '10%', y: '80%' }) + }.width('90%').height('100%').border({ width: 1, style: BorderStyle.Dashed }) + } + .width('90%').margin(25) + } + } + ``` + + ![](figures/position.gif) + + +## 自适应延伸 + +自适应延伸是在不同尺寸设备下,当页面显示内容个数不一并延伸到屏幕外时,可通过滚动条拖动展示。适用于线性布局中内容无法一屏展示的场景。常见以下两类实现方法。 + + +- List组件 + + List子项过多一屏放不下时,未展示的子项通过滚动条拖动显示。通过scrollBar属性设置滚动条的常驻状态,edgeEffect属性设置拖动到极限的回弹效果。 + + + 纵向List: + ```ts + @Entry + @Component + struct ListExample1 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listcolumn.gif) + + + 横向List: + + ```ts + @Entry + @Component + struct ListExample2 { + @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"] + @State alignListItem: ListItemAlign = ListItemAlign.Start + + build() { + Column() { + List({ space: 20, initialIndex: 0 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .height('100%') + .width(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .border({ width: 2, color: Color.Green }) + }, item => item) + } + .border({ width: 2, color: Color.Red, style: BorderStyle.Dashed }) + .scrollBar(BarState.On) // 滚动条常驻 + .edgeEffect(EdgeEffect.Spring) // 滚动到边缘再拖动回弹效果 + .listDirection(Axis.Horizontal) // 列表水平排列 + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20) + } + } + ``` + + ![](figures/listrow.gif) + +- Scroll组件 + + 线性布局中,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。在Column或者Row外层包裹一个可滚动的容器组件Scroll实现。 + + 纵向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Column() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .width('90%') + .height(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ top: 10 }) + }, item => item) + }.width('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Vertical) // 滚动方向纵向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + + ![](figures/scrollcolumn.gif) + + 横向Scroll: + + ```ts + @Entry + @Component + struct ScrollExample { + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + build() { + Scroll(this.scroller) { + Row() { + ForEach(this.arr, (item) => { + Text(item.toString()) + .height('90%') + .width(150) + .backgroundColor(0xFFFFFF) + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ left: 10 }) + }, item => item) + }.height('100%') + } + .backgroundColor(0xDCDCDC) + .scrollable(ScrollDirection.Horizontal) // 滚动方向横向 + .scrollBar(BarState.On) // 滚动条常驻显示 + .scrollBarColor(Color.Gray) // 滚动条颜色 + .scrollBarWidth(30) // 滚动条宽度 + .edgeEffect(EdgeEffect.Spring) // 滚动到边沿后回弹 + } + } + ``` + ![](figures/scrollrow.gif) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md index 27147d07fe719c98db76dd1a6ff57e3569a4faa6..100c4896116baa774b4f608a2764c356b5feef0c 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md @@ -1,27 +1,31 @@ # 媒体查询 +[媒体查询(Media Query)](../reference/apis/js-apis-mediaquery.md)作为响应式设计的核心,在移动设备上应用十分广泛。它根据不同设备类型或同设备不同状态修改应用的样式。媒体查询的优势有: -媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: +1. 提供丰富的媒体特征监听能力,针对设备和应用的属性信息(比如显示区域、深浅色、分辨率),设计出相匹配的布局。 +2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),同步更新应用的页面布局。 -1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 + -2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),应用页面布局同步更新。 +## 媒体查询引入与使用流程 +媒体查询通过媒体查询接口,设置查询条件并绑定回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑,实现页面的响应式设计。具体步骤如下: -## 如何使用 +首先导入媒体查询模块。 -通过调用媒体查询接口,设置媒体查询条件和查询结果的回调函数,在对应的条件的回调函数里更改页面布局或者实现业务逻辑。 - -首先导入媒体查询模块,例如: -``` +```ts import mediaquery from '@ohos.mediaquery' ``` -然后通过matchMediaSync接口设置媒体查询条件,并保存返回的条件监听句柄,例如: + +通过matchMediaSync接口设置媒体查询条件,保存返回的条件监听句柄listener。 + ```ts listener = mediaquery.matchMediaSync('(orientation: landscape)') ``` -最后通过上面保存的条件监听句柄listener去注册回调函数,在回调函数里更改页面布局或者实现业务逻辑,当匹配到媒体查询条件时会触发此回调函数,例如: + +给条件监听句柄listener绑定回调函数onPortrait,当listener检测设备状态变化时执行回调函数。在回调函数内,根据不同设备状态更改页面布局或者实现业务逻辑。 + ```ts onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { @@ -33,19 +37,25 @@ onPortrait(mediaQueryResult) { listener.on('change', onPortrait) ``` -## 媒体查询条件语法规则 +## 媒体查询条件 + +媒体查询条件由媒体类型,逻辑操作符,媒体特征组成,其中媒体类型可省略,逻辑操作符用于连接不同媒体类型与媒体特征,其中,媒体特征要使用()包裹且可以有多个。具体规则如下: + +### 语法规则 + ``` [media-type] [and|not|only] [(media-feature)] ``` + 例如: -`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立 +`screen and (round-screen: true)` :当设备屏幕是圆形时条件成立。 -`(max-height: 800)` :当高度小于800时条件成立 +`(max-height: 800)` :当高度小于等于800时条件成立。 -`(height <= 800) ` :当高度小于等于800时条件成立 +`(height <= 800) ` :当高度小于等于800时条件成立。 -`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询 +`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询,当设备类型为tv或设备分辨率小于2时条件成立。 ### 媒体类型(media-type) @@ -53,32 +63,30 @@ listener.on('change', onPortrait) | ------ | -------------- | | screen | 按屏幕相关参数进行媒体查询。 | +### 媒体逻辑操作(and|or|not|only) -### 媒体逻辑操作(and|not|only) - -媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(,)将其组合起来,详细解释说明如下表。 +媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(, )将其组合起来,详细解释说明如下表。 **表1** 媒体逻辑操作符 | 类型 | 说明 | | -------- | ---------------------------------------- | -| and | 将多个媒体特征(Media Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen and (device-type: wearable) and (max-height: 600) 表示当设备类型是智能穿戴同时应用的最大高度小于等于600个像素单位时成立。 | -| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。在媒体查询列表中应用not,则not仅取反应用它的媒体查询。
例如:not screen and (min-height: 50) and (max-height: 600) 表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | -| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen and (min-height: 50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | -| ,(comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen and (min-height: 1000),  (round-screen:true) 表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen and (max-height: 1000) or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| and | 将多个媒体特征(Media  Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen  and  (device-type:  wearable)  and  (max-height:  600)  表示当设备类型是智能穿戴且应用的最大高度小于等于600个像素单位时成立。 | +| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen  and  (max-height:  1000)  or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。
例如:not  screen  and  (min-height:  50)  and  (max-height:  600)  表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | +| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen  and  (min-height:  50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | +| , (comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen  and  (min-height:  1000),     (round-screen:true)  表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | -在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了<=,>=,<,>操作符。 +在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了< =,> =,< ,> 操作符。 **表2** 媒体逻辑范围操作符 | 类型 | 说明 | | ----- | ---------------------------------------- | -| <= | 小于等于,例如:screen and (50 <= height)。 | -| >= | 大于等于,例如:screen and (600 >= height)。 | -| < | 小于,例如:screen and (50 < height)。 | -| > | 大于,例如:screen and (600 > height)。 | - +| < = | 小于等于,例如:screen  and  (height  < =  50)。 | +| > = | 大于等于,例如:screen  and  (height  > =  600)。 | +| < | 小于,例如:screen  and  (height  <   50)。 | +| > | 大于,例如:screen  and  (height  >   600)。 | ### 媒体特征(media-feature) @@ -90,58 +98,59 @@ listener.on('change', onPortrait) | width | 应用页面显示区域的宽度。 | | min-width | 应用页面显示区域的最小宽度。 | | max-width | 应用页面显示区域的最大宽度。 | -| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
- dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
- dpcm表示每厘米上的物理像素个数,1dpcm ≈ 2.54dpi;
- dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx = 96dpi。 | +| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
-  dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
-  dpcm表示每厘米上的物理像素个数,1dpcm  ≈  2.54dpi;
-  dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx  =  96dpi。 | | min-resolution | 设备的最小分辨率。 | | max-resolution | 设备的最大分辨率。 | -| orientation | 屏幕的方向。
可选值:
- orientation: portrait(设备竖屏)
- orientation: landscape(设备横屏) | +| orientation | 屏幕的方向。
可选值:
-  orientation:  portrait(设备竖屏)
-  orientation:  landscape(设备横屏) | | device-height | 设备的高度。 | | min-device-height | 设备的最小高度。 | | max-device-height | 设备的最大高度。 | | device-width | 设备的宽度。 | | min-device-width | 设备的最小宽度。 | | max-device-width | 设备的最大宽度。 | -| round-screen | 屏幕类型,圆形屏幕为true, 非圆形屏幕为 false。 | +| round-screen | 屏幕类型,圆形屏幕为true,  非圆形屏幕为  false。 | | dark-mode | 系统为深色模式时为true,否则为false。 | ## 场景示例 -通过使用媒体查询实现当屏幕发生横竖屏切换,给页面文本应用不同的内容和样式。 - - ``` - import mediaquery from '@ohos.mediaquery' - let portraitFunc = null - - @Entry - @Component - struct MediaQueryExample { - @State color: string = '#DB7093' - @State text: string = 'Portrait' - @State fontSize: number = 24 - listener = mediaquery.matchMediaSync('(orientation: landscape)') - - onPortrait(mediaQueryResult) { - if (mediaQueryResult.matches) { - this.color = '#FFD700' - this.text = 'Landscape' - } else { - this.color = '#DB7093' - this.text = 'Portrait' - } - } - - aboutToAppear() { - portraitFunc = this.onPortrait.bind(this) //绑定当前应用实例 - this.listener.on('change', portraitFunc) +下例中使用媒体查询,实现屏幕横竖屏切换时给页面文本应用不同的内容和样式的效果。 + +```ts +import mediaquery from '@ohos.mediaquery' + +let portraitFunc = null + +@Entry +@Component +struct MediaQueryExample { + @State color: string = '#DB7093' + @State text: string = 'Portrait' + listener = mediaquery.matchMediaSync('(orientation: landscape)') // 当设备横屏时条件成立 + + onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + this.color = '#FFD700' + this.text = 'Landscape' + } else { + this.color = '#DB7093' + this.text = 'Portrait' } - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text(this.text).fontSize(50).fontColor(this.color) - } - .width('100%').height('100%') + } + + aboutToAppear() { + portraitFunc = this.onPortrait.bind(this) // 绑定当前应用实例 + this.listener.on('change', portraitFunc) + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.text).fontSize(50).fontColor(this.color) } + .width('100%').height('100%') } - ``` +} +``` + 横屏下文本内容为Landscape,颜色为#FFD700。 ![zh-cn_image_0000001262954829](figures/zh-cn_image_0000001262954829.png) @@ -152,7 +161,7 @@ listener.on('change', onPortrait) ## 相关实例 -针对媒体查询开发,有以下相关实例可供参考: +使用媒体查询的自适应布局开发,有以下相关实例可供参考: - [`MediaQuery`:媒体查询(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-stack.md b/zh-cn/application-dev/ui/ui-ts-layout-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..63904bd277cea803b4c9147ebf618be26e561d02 --- /dev/null +++ b/zh-cn/application-dev/ui/ui-ts-layout-stack.md @@ -0,0 +1,61 @@ +# 层叠布局 + +层叠布局(StackLayout)用于在屏幕上预留一块区域来显示组件中的元素,提供元素可以重叠的布局。 +通过层叠容器[Stack](../reference/arkui-ts/ts-container-stack.md)实现,容器中的子元素依次入栈,后一个子元素覆盖前一个子元素显示。 + +## 对齐方式 + +设置子元素在容器内的对齐方式。支持左上,上中,右上,左,中,右,右下,中下,右下九种对齐方式,如下表所示: + +|名称| 描述| 图示 | +|---| ---|---| +|TopStart| 顶部起始端 |![](figures/stacktopstart.png)| +Top |顶部横向居中 |![](figures/stacktop.png)| +TopEnd| 顶部尾端 |![](figures/stacktopend.png)| +Start| 起始端纵向居中 |![](figures/stackstart.png)| +Center| 横向和纵向居中 |![](figures/stackcenter.png)| +End| 尾端纵向居中 |![](figures/stackend.png)| +BottomStart |底部起始端 |![](figures/stackbottomstart.png)| +Bottom| 底部横向居中 |![](figures/stackbottom.png)| +BottomEnd| 底部尾端 |![](figures/stackbottomend.png)| + +## Z序控制 + +Stack容器中兄弟组件显示层级关系可以通过[zIndex](../reference/arkui-ts/ts-universal-attributes-z-order.md) +属性改变。zIndex值越大,显示层级越高,即zIndex值大的组件会覆盖在zIndex值小的组件上方。 + +- 在层叠布局中,如果后面子元素尺寸大于前面子元素尺寸,则前面子元素完全隐藏。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack2.png) + + 上图中,最后的子元素3的尺寸大于前面的所有子元素,所以,前面两个元素完全隐藏。改变子元素1,子元素2的zIndex属性后,可以将元素展示出来。 + + ```ts + Stack({ alignContent: Alignment.BottomStart }) { + Column() { + Text('Stack子元素1').textAlign(TextAlign.End).fontSize(20) + }.width(100).height(100).backgroundColor(0xffd306).zIndex(2) + Column() { + Text('Stack子元素2').fontSize(20) + }.width(150).height(150).backgroundColor(Color.Pink).zIndex(1) + Column() { + Text('Stack子元素3').fontSize(20) + }.width(200).height(200).backgroundColor(Color.Grey) + }.margin({ top: 100 }).width(350).height(350).backgroundColor(0xe0e0e0) + ``` + + ![](figures/stack1.png) diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index 348ce1cde17b33f3a6bb7fe393e74427f6852a63..7c6d9bf7771d91be396b6f5b94ad6eb881024a1a 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -1,30 +1,25 @@ # 概述 -基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、跨设备应用的UI开发框架,支持开发者高效的构建跨设备应用UI界面。 +基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、支持跨设备的UI开发框架,支持开发者高效地构建OpenHarmony应用UI界面。 ## 基础能力 -使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动效和状态管理三个维度来提供UI能力,还提供了系统能力接口,实现系统能力的极简调用。 - -请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解组件,更好地开发应用。 - +使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动画和状态管理三个维度来提供UI能力,还提供了系统能力接口以实现系统能力的极简调用。 +ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get-started.md)文档;此外,请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解内置组件,更好地开发应用。 - **开箱即用的组件** - 框架提供丰富的系统预置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - + 框架提供丰富的系统内置组件,可以通过链式调用的方式设置系统组件的渲染效果。开发者可以组合系统组件为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,使页面具有更强的工程性。 - **丰富的动效接口** 提供svg标准的绘制图形能力,同时开放了丰富的动效接口,开发者可以通过封装的物理模型或者调用动画能力接口来实现自定义动画轨迹。 - - **状态与数据管理** 状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。 - - **系统能力接口** 使用基于ArkTS的声明式开发范式的方舟开发框架,还封装了丰富的系统能力接口,开发者可以通过简单的接口调用,实现从UI设计到系统能力调用的极简开发。 @@ -32,8 +27,6 @@ ## 整体架构 - - ![zh-cn_image_0000001169532276](figures/zh-cn_image_0000001169532276.png) - **声明式UI前端** @@ -50,7 +43,7 @@ - **渲染引擎** - 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕能力。 + 提供了高效的绘制能力,将渲染管线收集的渲染指令,绘制到屏幕的能力。 - **平台适配层** diff --git a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md similarity index 94% rename from zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md rename to zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md index e37724ed2f5d44cf9557e36bcc072f7430a81658..8a0b469305af0bb990edc42c04ef09c7cf65f189 100644 --- a/zh-cn/application-dev/ui/ts-performance-improvement-recommendation.md +++ b/zh-cn/application-dev/ui/ui-ts-performance-improvement-recommendation.md @@ -127,6 +127,8 @@ struct MyComponent { } ``` +![LazyForEach1](figures/LazyForEach1.gif) + 上述代码在页面加载时仅初始化加载三个列表元素,之后每点击一次列表元素,将增加一个列表元素。 ## 使用条件渲染替代显隐控制 @@ -179,6 +181,8 @@ struct MyComponent { } ``` +![isVisible](figures/isVisible.gif) + ## 使用Column/Row替代Flex 由于Flex容器组件默认情况下存在shrink导致二次布局,这会在一定程度上造成页面渲染上的性能劣化。 @@ -213,6 +217,8 @@ struct MyComponent { } ``` +![flex1](figures/flex1.PNG) + ## 设置List组件的宽高 开发者在使用Scroll容器组件嵌套List子组件时,若不指定List的宽高尺寸,则默认全部加载,如下所示: @@ -259,7 +265,10 @@ struct MyComponent { } ``` +![list1](figures/list1.gif) + ## 减少应用滑动白块 + 应用通过增大List/Grid控件的cachedCount参数,调整UI的加载范围。cachedCount表示屏幕外List/Grid预加载item的个数。 如果需要请求网络图片,可以在item滑动到屏幕显示之前,提前下载好内容,从而减少滑动白块。 如下是使用cachedCount参数的例子: @@ -269,33 +278,41 @@ struct MyComponent { @Component struct MyComponent { private source: MyDataSource = new MyDataSource(); + build() { List() { - LazyForEach (this.source, item => { + LazyForEach(this.source, item => { ListItem() { Text("Hello" + item) - .fontSize(100) - .onAppear(()=>{ + .fontSize(50) + .onAppear(() => { console.log("appear:" + item) }) } }) - }.cachedCount(3) // 扩大数值appear日志范围会变大 + }.cachedCount(3) // 扩大数值appear日志范围会变大 } } + class MyDataSource implements IDataSource { - data: number[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; + data: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + public totalCount(): number { return this.data.length } + public getData(index: number): any { return this.data[index] } + registerDataChangeListener(listener: DataChangeListener): void { } + unregisterDataChangeListener(listener: DataChangeListener): void { } } ``` +![list2](figures/list2.gif) + **使用说明:** cachedCount的增加会增大UI的cpu、内存开销。使用时需要根据实际情况,综合性能和用户体验进行调整。 \ No newline at end of file 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/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 661d379df7f0e29626aab080c37eeb092a68a67a..51b969f34e611a7a23ee8f115389590737b11a11 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -396,4 +396,4 @@ class MainAbility extends Ability { 针对window开发(Stage模型),有以下相关实例可供参考: -- [`Window`:窗口(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) \ No newline at end of file +- [`Window`:窗口(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) \ No newline at end of file diff --git "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" index 4006d5a1d8b7f384eb1169e6867b5f97d35b02ad..ae8a73e9c771c7a42ce662c325c43d4990f82182 100755 --- "a/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" +++ "b/zh-cn/contribute/\350\264\241\347\214\256\344\273\243\347\240\201.md" @@ -10,7 +10,7 @@ [OpenHarmony安全设计规范](OpenHarmony-security-design-guide.md) -[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-QA/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) +[OpenHarmony编译规范](https://gitee.com/openharmony/community/blob/master/sig/sig-buildsystem/%E7%BC%96%E8%AF%91%E8%A7%84%E8%8C%83.md) ### 代码风格 diff --git a/zh-cn/device-dev/device-test/figures/FAQ-1.PNG b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..bebb315141c4cc3c004b502bb288705c8af9ebd8 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/FAQ-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/L0-1.PNG b/zh-cn/device-dev/device-test/figures/L0-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..35fb66bafc980f97f755d09f26ed682737d371a0 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/L0-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-1.PNG b/zh-cn/device-dev/device-test/figures/NFS-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5fd5fb4f9063c00f1041eea1bb87b1b2519852cc Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-1.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-2.PNG b/zh-cn/device-dev/device-test/figures/NFS-2.PNG new file mode 100644 index 0000000000000000000000000000000000000000..0cd6f271936b2ee4fa97b256263bf85ba76c833b Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-2.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/NFS-3.PNG b/zh-cn/device-dev/device-test/figures/NFS-3.PNG new file mode 100644 index 0000000000000000000000000000000000000000..5a76e272ff763f3e31421d7c50c80f70febf1ce9 Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/NFS-3.PNG differ diff --git a/zh-cn/device-dev/device-test/figures/result-1.PNG b/zh-cn/device-dev/device-test/figures/result-1.PNG new file mode 100644 index 0000000000000000000000000000000000000000..64c730feade073029102459e92c01f8ff885f51d Binary files /dev/null and b/zh-cn/device-dev/device-test/figures/result-1.PNG differ diff --git a/zh-cn/device-dev/device-test/xdevice.md b/zh-cn/device-dev/device-test/xdevice.md new file mode 100644 index 0000000000000000000000000000000000000000..54662ecf75e2248d40b287edba9ead3fc3f9e491 --- /dev/null +++ b/zh-cn/device-dev/device-test/xdevice.md @@ -0,0 +1,706 @@ +# xDevice测试调度执行框架使用指南 + + +## 概述 + +OpenHarmony开源操作系统有众多芯片场景基于其之上进行开发版本等相关产品的开发,为了保障OpenHarmony生态的兼容性,OpenHarmony提供了[兼容性测试测评服务](https://www.openharmony.cn/certification/document/guid),其中针对产品需要进行接口相关的测试执行验证,但是大量自动化用例的执行需要一套调度执行框架,并且支持生成可视化的测试报告等能力,故我们设计并开发了xdevice测试调度框架来支持该场景。 + +### 简介 + +xDevice测试调度框架是OpenHarmony中测试基础设施的核心组件,提供调度自动化用例执行所依赖的相关服务,支持大量自动化用例的调度执行能力,并可自带生成可视化测试报告。而xDevice二进制包会跟踪随OpenHarmony的XTS套件编译,开发者可以从XTS套件归档路径中获取xDevice工具, + +根据设备类型的不同,xDevice主要测试的任务场景有以下三个: + +- 对轻量系统设备进行XTS测试(如:Hi3861开发板) +- 对小型系统设备进行XTS测试(如:Hi3516开发板) +- 对标准系统设备进行XTS测试(如:RK3568开发板) + +### 实现原理 + +xDevice包括以下功能模块: + +- command:用户与测试平台命令行交互模块,提供用户输入命令解析,命令处理。 +- config:测试框架配置模块,提供测试平台串口连接方式和USB连接方式的不同配置选项。 +- driver:测试用例执行器,提供测试用例分发,执行,结果收集等主要测试步骤定义。 +- report:测试报告模块,提供测试结果解析和测试报告生成。 +- scheduler:测试框架调度模块,提供不同类型的测试执行器调度的调度功能。 +- environment:测试框架的环境配置模块,提供设备发现,设备管理的功能。 +- testkit:测试框架工具模块,提供json解析,网络文件挂载等操作。 +- log:测试框架日志模块,提供记录任务日志以及设备日志的功能。 + +除了上述功能模块之外,测试调度框架还依赖了用户自定义配置文件,配置文件主要分为两类。 + +**测试任务配置文件** + +user_config.xml是框架提供的测试任务配置文件,用户可以根据自身环境信息配置相关内容,主要包括以下配置内容。 + +environment环境相关配置,详解介绍如下。 + +```xml + + + + + + + + + + + + + + cmd + 115200 + 8 + 1 + 20 + + + + deploy + 115200 + + + + + + + + cmd + 115200 + 8 + 1 + 1 + + + + + + + + + +``` + +测试用例目录设置。 + +```xml + + + + + + + + + + + + + + + +``` + +资源目录设置。 + +```xml + + + + +``` + +日志打印级别设置。 + +```xml + +INFO +``` + +**测试套配置文件** + +设备执行的测试支撑套件是由测试配置文件所指定。 + +每个测试套都都有一个测试配置文件,主要配置了需要使用的测试支撑套件(kits)等信息,并支持配置执行预制和清理操作。 + +以下为配置文件样例。 + +```json +{ + // 测试支撑套件描述 + "description": "Configuration for aceceshi Tests", + + // 指定执行当前测试支撑套的设备 + "environment": { + "type": "device", + "label": "wifiiot" + }, + + // 指定设备执行的驱动 + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "700000", + "bundle-name": "com.open.harmony.acetestfive", + "package-name": "com.open.harmony.acetestfive", + "shell-timeout": "700000" + }, + // kit的作用主要是为了支撑测试执行活动,在测试前执行预制操作(Setup),在测试后执行清理操作(Teardown) + "kits": [ + { + "type": "ShellKit", + "run-command": [ + "remount", + "mkdir /data/data/resource", + "chmod -R 777 /data/data/resource", + "settings put secure adb_install_need_confirm 0" + ], + "teardown-command": [ + "remount", + "rm -rf /data/data/resource" + ] + }, + ] +} +``` + +### 测试命令 + +测试命令可以分为三组:help、list、run。在指令序列中,以run为最常用的执行指令。 + +------ + +输入help指令可以查询框架指令帮助信息。 + +```text +help: + use help to get information. +usage: + run: Display a list of supported run command. + list: Display a list of supported device and task record. +Examples: + help run + help list +``` + +**说明:** + +help run:展示run指令相关说明 。 + +help list:展示 list指令相关说明。 + +------ + +list指令用来展示设备和相关的任务信息。 + +```text +list: + This command is used to display device list and task record. +usage: + list + list history + list +Introduction: + list: display device list + list history: display history record of a serial of tasks + list : display history record about task what contains specific id +Examples: + list + list history + list 6e****90 +``` + + **说明:** + + list: 展示设备信息。 + + list history: 展示任务历史信息 。 + + list : 展示特定id的任务其历史信息。 + +------ + +run指令主要用于执行测试任务。 + +```text +run: + This command is used to execute the selected testcases. + It includes a series of processes such as use case compilation, execution, and result collection. +usage: run [-l TESTLIST [TESTLIST ...] | -tf TESTFILE + [TESTFILE ...]] [-tc TESTCASE] [-c CONFIG] [-sn DEVICE_SN] + [-rp REPORT_PATH [REPORT_PATH ...]] + [-respath RESOURCE_PATH [RESOURCE_PATH ...]] + [-tcpath TESTCASES_PATH [TESTCASES_PATH ...]] + [-ta TESTARGS [TESTARGS ...]] [-pt] + [-env TEST_ENVIRONMENT [TEST_ENVIRONMENT ...]] + [-e EXECTYPE] [-t [TESTTYPE [TESTTYPE ...]]] + [-td TESTDRIVER] [-tl TESTLEVEL] [-bv BUILD_VARIANT] + [-cov COVERAGE] [--retry RETRY] [--session SESSION] + [--dryrun] [--reboot-per-module] [--check-device] + [--repeat REPEAT] + action task +Specify tests to run. + positional arguments: + action Specify action + task Specify task name,such as "ssts", "acts", "hits" +``` + +run指令基本使用方法如下。 + +| xDevice命令 | 功能 | 示例 | +| :----------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| run xts | 运行所有指定类型的XTS模块,如acts,hits,ssys等 | run acts | +| run -l xxx | 运行指定的模块测试套,模块间用分号隔离 | run -l ActsWifiServiceTest;ActsLwipTest | +| run -sn | 指定运行设备的SN号,多个SN号用分号隔离 | run acts -sn 10.117.183.37:17001
run acts -sn 88Y02******57723;VEG02******16642 | +| run -rp | 指定报告生成的路径,默认会在工作目录的reports下用时间戳或任务ID建立子目录 | run acts -rp /suites/hits/xdevice_reports/2020.09.28-14.21.26 | +| run -respath | 指定测试资源路径,默认为resource目录 | run acts -respath /cloud/zidane/xts/release/suites/resource | +| run -ta | 指定模块运行参数,可以指定运行模块用例中指定的用例,多个用例用逗号隔离,目前支持JS驱动测试套 | run acts -ta class:ohos.hardware.soundtrigger.SoundTriggerTest#testKeyphraseParcelUnparcel_noUsers | +| run --retry | 重新运行上一次任务的失败用例,生成新的测试报告 | run –retryrun --retry --session 2020-10-30-17-15-11(任务目录名) | + +### 测试报告 + +框架执行run指令,控制台会输出对应的log打印,还会生成对应的执行结果报告。如果使用了-rp参数指定报告路径,那么报告就会生成在指定的路径下。否则报告会存放在默认目录。 + +```text +当前报告目录(默认目录/指定目录) + ├── result(模块执行结果存放目录) + │ ├── <模块名>.xml + │ ├── ... ... + │ + ├── log (设备和任务运行log存放目录) + │ ├── <设备1>.log + │ ├── ... ... + │ ├── <任务>.log + ├── summary_report.xml(任务汇总数据报告) + ├── summary_report.html(任务汇总可视化报告) + ├── details_report.html(用例执性可视化报告) + ├── failures_report.html(失败用例可视化报告,无失败用例时不生成) + ├── summary.ini(记录测试类型,使用的设备,开始和结束时间等信息) + ├── task_info.record(记录执行命令,失败用例清单等信息) + ├── xxxx.zip(对上述文件进行压缩得到的压缩文件) + ├── summary_report.hash(对压缩文件进行sha256加密得到的文件) + └── ... ... +``` + + +## 环境准备 + + +### 环境要求 + +- python版本>=3.7 +- pyserial>=3.3 +- paramiko>=2.7.1 +- rsa>=4.0 + + +### 安装xDevice + +- 安装基础框架xDevice。 + + 1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + + 2. 打开控制台,执行如下命令。 + + ```bash + python setup.py install + ``` + +- 安装OpenHarmony驱动插件ohos。 + + 1. 进行plugin/ohos目录。 + + ```bash + cd testfwk_xdevice/plugin/ohos + ``` + + 2. 打开控制台,当前用户下执行如下命令。 + + ```bash + python setup.py install + ``` + +### 检验环境是否搭建成功 + +检验xDevice是否安装成功。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m pip list + ``` + +3. 查看是否已经成功安装**xdevice**以及**xdevice-ohos**两个库。 + + ```text + xdevice 0.0.0 + xdevice-ohos 0.0.0 + ``` + +查看xDevice工具是否能够正常运行。 + +1. 进入xDevice根目录。 + + ```bash + cd testfwk_xdevice + ``` + +2. 打开控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + +3. 查看控制台是否正常输出如下信息。 + + ```text + [2022-10-13 15:43:31,284] [30076] [Main] [INFO] [*************** xDevice Test Framework 2.11.0.1091 Starting ***************] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [wifiiot local com cannot be empty, please check] + [2022-10-13 15:43:31,286] [30076] [ManagerLite] [WARNING] [ipcamera local com cannot be empty, please check] + [2022-10-13 15:43:31,287] [30076] [ManagerLite] [WARNING] [device com or ip cannot be empty, please check] + >>> + ``` + + +## 轻量系统设备XTS测试指导(wifiiot) + +1. 识别串口用途,修改根目录中的user_config.xml文件。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + type为deploy的com口对应板子上的日志输出串口,用于镜像烧录和日志打印,示例中配置为ChB(COM18)串口号。 + + 若AT命令串口和日志输出串口共用,可以配置为相同,即user_config中的type为cmd的com口与type为deploy的com口可配置为一样的端口,如COM18。 + + ![L0-1](figures/L0-1.PNG) + + user_config.xml的修改示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 20 + + + com18 + deploy + 115200 + + + + + + + + + + + + + + + + + + DEBUG + + ``` + +2. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for ActsAllTest test cases", + "environment": [ + { + "type": "device", + "label": "wifiiot" + } + ], + "kits": [ + { + "type": "DeployKit", + "timeout": "20000", + "burn_file": "acts/Hi3861_wifiiot_app_allinone.bin" + } + ], + "driver": { + "type": "CTestLite" + } + } + ``` + +3. 执行用例 + + 进入xDevice根目录;打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActsAllTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 小型系统设备XTS测试指导(ipcamera) + +1. 识别串口用途。 + + type为cmd的com口对应板子上的AT命令串口,用于对设备发送指令,示例中配置为ChA(COM20)串口号。 + + L0-1 + + ipcamera设备有两种连接方式,一种是本地串口连接,一种是通过局域网ip连接。 + +2. 配置NFS服务器 + + NFS挂载方式有两种,一种是远程PC挂载方式,一种是本地局域网挂载方式。 + + 本地局域网NFS服务的配置方法如下。 + + 1. 下载安装NFS服务器。下载地址:https://www.hanewin.net/nfs-e.htm + + 2. 配置输出->编辑输出表文件。 + + + + 3. 添加路径NFS共享路径(如:D:\HS\NFS_Share_File -public –alldirs),这里要注意ftp的IP地址192.168.1.10为开发板的IP。 + + + + 4. 停止NFS服务器->重启运行NFS服务器使刚才添加的共享路径生效。 + + 5. 找到ipcamera设备在PC上面映射的网口:控制面板->网络和Internet->网络共享中心->以太网状态->以太网属性->手动设置IP地址为:192.168.1.11。 + + + +3. 修改根目录中的user_config.xml文件,示例如下。 + + ```xml + + + + + com20 + cmd + 115200 + 8 + 1 + 1 + + + + 10.176.49.47 + 10003 + + + + + + 10.176.48.202 + 1022 + /data/data/local/ + root + xxx + true + + + 192.168.1.11 + 2049 + D:\test + false + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Config for kernel test cases", + "environment": [ + { + "type": "device", + "label": "ipcamera" + } + ], + "kits": [ + { + "type": "MountKit", + "server": "NfsServer", + "mount": [ + { + "source": "testcases/kernel", + "target": "/test_root/kernel" + } + ] + } + ], + "driver": { + "type": "CppTestLite", + "excute": "/test_root/kernel/ActsKernelIPCTest.bin" + } + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l kernel + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 标准系统设备XTS测试指导(RK3568) + +1. 配置hdc工具,从每日构建上下载ohos_sdk最新版本即可。 + + 每日构建地址:http://ci.openharmony.cn/dailys/dailybuilds + + 下载工具后,把hdc配置到环境变量中,配置方法:右键单击我的电脑->属性->高级系统设置->环境变量->Path。 + +2. 执行如下命令查看设备是否正常连接。 + + ```bash + hdc_std list targets + ``` + +3. 修改user_config.xml文件,示例如下。 + + ```xml + + + + + + xxx;xxx + + + + + + + + + DEBUG + + ``` + +4. 在xDevice根目录下新建testcase文件夹用于存放测试套文件,具体XTS测试套从系统构建的每日构建中获取。 + + 每日构建:http://ci.openharmony.cn/dailys/dailybuilds + + 测试套测试配置文件json,示例如下。 + + ```json + { + "description": "Configuration for hjunit demo Tests", + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "180000", + "bundle-name": "ohos.acts.bundle.stage.test", + "module-name": "phone", + "shell-timeout": "600000", + "testcase-timeout": 70000 + }, + "kits": [ + { + "test-file-name": [ + "ActBmsStageEtsTest.hap" + ], + "type": "AppInstallKit", + "cleanup-apps": true + }, + { + "type": "ShellKit", + "teardown-command":[ + "bm uninstall -n ohos.acts.bundle.stage.test" + ] + } + ] + } + ``` + +5. 执行用例。 + + 进入xDevice根目录,打开控制台进入xDevice控制台,执行如下命令。 + + ```bash + python -m xdevice + ``` + + 执行测试套命令。 + + ```text + run -l ActBmsStageEtsTest + ``` + + 执行结果如下。 + + ![result-1](figures/result-1.PNG) + +## 常见问题 + +### hdc list targets能查找到设备,但xDevice识别不到设备。 + +**问题描述** + +出现如下错误。 + +![FAQ-1](figures/FAQ-1.PNG) + +**可能原因** + +环境变量中曾设置过HDC_SERVER_PORT变量修改过hdc的端口,由于xDevice默认需要使用8710端口,若曾修改过该端口会导致xDevice框架无法识别设备。 + +**解决方法** + +检查是否有设置HDC_SERVER_PROT变量,若有设置,请把该端口的值修改为8710,然后重启xDevice即可。 + 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/faqs/faqs-startup.md b/zh-cn/device-dev/faqs/faqs-startup.md index 9db1d8a011326bf14d1a272f5703656899f0b3d7..d1c02d9d674dc1a9202a1bbca80bca265cf1a614 100644 --- a/zh-cn/device-dev/faqs/faqs-startup.md +++ b/zh-cn/device-dev/faqs/faqs-startup.md @@ -191,6 +191,42 @@ OpenHarmony-3.0-LTS 设备进入hdc shell下, 执行sandbox -s service_name命令,模拟当前服务进入沙盒场景, 通过 ls 等shell命令查看当前服务沙盒目录。具体参考[沙盒命令](../subsystems/subsys-boot-init-plugin.md) +### Bootevent部分事件的ready阶段的时间戳为0 + +**现象描述** + +Bootevent手动模式下,开机完成之后在执行dump_service all bootevent命令后有部分事件的ready阶段的时间戳为0。 + +**可能原因** + +1. 服务没有发送bootevent事件。 +2. 服务发送bootevent事件, 但是没有相关权限。 + +**解决方法** + +1. 服务配置了bootevent,但是没有发送该bootevent事件,请相关服务在代码中发送该bootevent事件。 +2. 在代码中已经执行到设置bootevent的操作,但是ready的状态就是为零,此时请检查服务是否有设置bootevent参数的权限。 + +### A/B分区启动过程因只烧写原始分区导致的无法启动 + +**现象描述** + +烧写完成后系统无法正常启动,并且可以在串口日志中找到类似如下打印: + +``` +wait for file:/dev/block/platform/fe310000.sdhci/by-name/system_b failed after 5 second. +Mount /dev/block/platform/fe310000.sdhci/by-name/system_b to /usr failed 2 +``` + +**可能原因** + +当前系统已经支持了A/B分区启动,根据日志可知本次启动尝试挂载了带"_b"后缀的system分区,即本次启动从B分区启动,但是并没有找到设备,导致挂载失败。这种情况是由于当前misc分区中的active slot值被设置为了2(B分区),但是并没有烧写对应B分区导致的。 + +**解决方法** + +1. 可以清空misc分区(使用空misc镜像烧写对应分区),将其中的active slot值擦除,再次启动即可从默认分区启动。 +2. 使用配置了B分区的分区表将system_b和vendor_b镜像烧写到开发板中,再次启动即可从对应B分区正常启动。 + ## Appspawn应用孵化常见问题 ### 设备启动中,appspawn启动失败 @@ -221,11 +257,15 @@ OpenHarmony-3.0-LTS 1. 冷启动状态未打开。 2. 冷启动命令参数输入错误。 +3. socket请求超时。 +4. selinux打开。 **解决办法** -1. 冷启动不使能, 通过param get appspawn.cold.boot命令查看状态,如果冷启动状态是false, 通过param set appspawn.cold.boot true 命令打开冷启动状态。 +1. 冷启动不使能, 通过param get startup.appspawn.cold.boot命令查看状态,如果冷启动状态是0, 通过param set startup.appspawn.cold.boot 1 命令打开冷启动状态。 2. 冷启动命令参数不正确, 查看并确认冷启动参数。 +3. 设置超时时间>3秒,执行 param set persist.appspawn.client.timeout 5 命令。 +4. 关闭selinux, 执行 setenforce 0 命令。 ### 应用沙盒创建失败 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/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index d243354b9c95f462dcddd8fcb6ef7acd396b62d9..d2f636772b96b25854cf596fcb122bc9c08a561b 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -13,8 +13,9 @@ - [互斥锁](kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel-mini-basic-ipc-queue.md) - [信号量](kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel-basic-mini-time.md) + - [时间管理](kernel-mini-basic-time.md) - [软件定时器](kernel-mini-basic-soft.md) + - [双向链表](kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel-mini-extend-support.md) - [CPU占用率](kernel-mini-extend-cpup.md) @@ -27,7 +28,6 @@ - [LMS调测](kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel-mini-appx-code.md) - - [双向链表](kernel-mini-appx-data-list.md) - [标准库支持](kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel-small-overview.md) 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/kernel/kernel-mini-basic-interrupt.md b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md index 9c8e2e42ded8903ddaa5a864aea95bef8990e043..eaa1f10f6dc98b1ac1b6d6ddbda1d47af85fbf04 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-interrupt.md @@ -9,25 +9,25 @@ 下面介绍下中断的相关概念: -- 中断号 +- 中断号: 中断请求信号特定的标志,计算机能够根据中断号判断是哪个设备提出的中断请求。 -- 中断请求 +- 中断请求: “紧急事件”向CPU提出申请(发一个电脉冲信号),请求中断,需要CPU暂停当前执行的任务处理该“紧急事件”,这一过程称为中断请求。 -- 中断优先级 +- 中断优先级: 为使系统能够及时响应并处理所有中断,系统根据中断事件的重要性和紧迫程度,将中断源分为若干个级别,称作中断优先级。 -- 中断处理程序 +- 中断处理程序: 当外设发出中断请求后,CPU暂停当前的任务,转而响应中断请求,即执行中断处理程序。产生中断的每个设备都有相应的中断处理程序。 -- 中断触发 +- 中断触发: 中断源向中断控制器发送中断信号,中断控制器对中断进行仲裁,确定优先级,将中断信号发送给CPU。中断源产生中断信号的时候,会将中断触发器置“1”,表明该中断源产生了中断,要求CPU去响应该中断。 -- 中断向量 +- 中断向量: 中断服务程序的入口地址。 -- 中断向量表 +- 中断向量表: 存储中断向量的存储区,中断向量与中断号对应,中断向量在中断向量表中按照中断号顺序存储。 @@ -37,37 +37,46 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 **表1** 创建、删除中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| HalHwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | -| HalHwiDelete | 根据指定的中断号,删除中断。 | +| LOS_HwiCreate | 中断创建,注册中断号、中断触发模式、中断优先级、中断处理程序。中断被触发时,会调用该中断处理程序。 | +| LOS_HwiDelete | 根据指定的中断号,删除中断。 | **表2** 打开、关闭中断 -| 接口名 | 描述 | +| 接口名 | 描述 | | -------- | -------- | -| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | -| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | -| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | +| LOS_IntUnLock | 开中断,使能当前处理器所有中断响应。 | +| LOS_IntLock | 关中断,关闭当前处理器所有中断响应。 | +| LOS_IntRestore | 恢复到使用LOS_IntLock、LOS_IntUnLock操作之前的中断状态。 | + + **表3** 其他中断操作 + +| 接口名 | 描述 | +| :----------------- | ---------------- | +| LOS_HwiTrigger | 中断触发。 | +| LOS_HwiEnable | 中断使能。 | +| LOS_HwiDisable | 中断禁用。 | +| LOS_HwiClear | 中断手动清除。 | +| LOS_HwiSetPriority | 设置中断优先级。 | +| LOS_HwiCurIrqNum | 获取当前中断号。 | ## 开发流程 -1. 调用中断创建接口HalHwiCreate创建中断。 +1. 调用中断创建接口LOS_HwiCreate创建中断。 -2. 调用TestHwiTrigger接口触发指定中断(该接口在测试套中定义,通过写中断控制器的相关寄存器模拟外部中断,一般的外设设备,不需要执行这一步)。 +2. 调用LOS_HwiTrigger接口触发指定中断(写中断控制器的相关寄存器模拟外部中断),或通过外设触发中断。 -3. 调用HalHwiDelete接口删除指定中断,此接口根据实际情况使用,判断是否需要删除中断。 +3. 调用LOS_HwiDelete接口删除指定中断,此接口根据实际情况使用,开发者判断是否需要删除中断。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 根据具体硬件,配置支持的最大中断数及可设置的中断优先级个数。 -> -> - 中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 -> +> - 关中断时间或中断处理程序耗时不能过长,否则会影响CPU对中断的及时响应。 > - 中断响应过程中不能直接、间接执行引起调度的LOS_Schedule等函数。 -> -> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 +> - 中断恢复LOS_IntRestore()的入参必须是与之对应的LOS_IntLock()的返回值(即关中断之前的CPSR值)。 +> - Cortex-M系列处理器中0-15中断为内部使用,因此不建议用户去申请和创建。 ## 编程实例 @@ -80,29 +89,39 @@ OpenHarmony LiteOS-M内核的中断模块提供下面几种功能,接口详细 3. 删除中断。 -代码实现如下,演示如何创建中断和删除中断,当指定的中断号HWI_NUM_TEST产生中断时,会调用中断处理函数: +代码实现如下,演示如何创建中断、触发指定的中断号进而调用中断处理函数、删除中断。 + +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleInterrupt。 + - ``` #include "los_interrupt.h" +#include "los_compiler.h" -/*创建中断*/ +/* 验证的中断号 */ #define HWI_NUM_TEST 7 -STATIC VOID HwiUsrIrq(VOID) +/* 中断处理程序 */ +STATIC VOID UsrIrqEntry(VOID) { - printf("in the func HwiUsrIrq \n"); + printf("in the func UsrIrqEntry\n"); } -static UINT32 Example_Interrupt(VOID) +/* 注册的线程回调函数,用于触发中断 */ +STATIC VOID InterruptTest(VOID) +{ + LOS_HwiTrigger(HWI_NUM_TEST); +} + +UINT32 ExampleInterrupt(VOID) { UINT32 ret; - HWI_PRIOR_T hwiPrio = 3; + HWI_PRIOR_T hwiPrio = 3; // 3,中断优先级 HWI_MODE_T mode = 0; HWI_ARG_T arg = 0; - - /*创建中断*/ - ret = HalHwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)HwiUsrIrq, arg); + + /* 创建中断 */ + ret = LOS_HwiCreate(HWI_NUM_TEST, hwiPrio, mode, (HWI_PROC_FUNC)UsrIrqEntry, arg); if(ret == LOS_OK){ printf("Hwi create success!\n"); } else { @@ -110,17 +129,32 @@ static UINT32 Example_Interrupt(VOID) return LOS_NOK; } - /* 延时50个Ticks, 当有硬件中断发生时,会调用函数HwiUsrIrq*/ + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 testTaskID; + + /* 创建一个优先级低优先级的线程,用于验证触发中断 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)InterruptTest; + taskParam.uwStackSize = OS_TSK_TEST_STACK_SIZE; + taskParam.pcName = "InterruptTest"; + taskParam.usTaskPrio = TASK_PRIO_TEST - 1; + taskParam.uwResved = LOS_TASK_ATTR_JOINABLE; + ret = LOS_TaskCreate(&testTaskID, &taskParam); + if (LOS_OK != ret) { + PRINTF("InterruptTest task error\n"); + } + + /* 延时50 tick,让出当前线程的调度 */ LOS_TaskDelay(50); - /*删除中断*/ - ret = HalHwiDelete(HWI_NUM_TEST); + /* 删除注册的中断 */ + ret = LOS_HwiDelete(HWI_NUM_TEST, NULL); if(ret == LOS_OK){ printf("Hwi delete success!\n"); } else { printf("Hwi delete failed!\n"); return LOS_NOK; } + return LOS_OK; } ``` @@ -131,8 +165,9 @@ static UINT32 Example_Interrupt(VOID) 编译运行得到的结果为: - + ``` Hwi create success! +in the func UsrIrqEntry Hwi delete success! ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md index 3f22c8ca8805c838933f2a66cead333a6ae34e04..ef398c91849fcae751bcb1c848424acaa609772d 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -16,14 +16,12 @@ ## 运行机制 - ### 事件控制块 +由事件初始化函数配置的一个结构体,在事件读写等操作时作为参数传入,用于标识不同的事件,控制块数据结构如下: + ``` -/** - * 事件控制块数据结构 - */ typedef struct tagEvent { UINT32 uwEventID; /* 事件集合,表示已经处理(写入和清零)的事件集合 */ LOS_DL_LIST stEventList; /* 等待特定事件的任务链表 */ @@ -33,7 +31,7 @@ typedef struct tagEvent { ### 事件运作原理 -**事件初始化**:会创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 +**事件初始化**:创建一个事件控制块,该控制块维护一个已处理的事件集合,以及等待特定事件的任务链表。 **写事件**:会向事件控制块写入指定的事件,事件控制块更新事件集合,并遍历任务链表,根据任务等待具体条件满足情况决定是否唤醒相关任务。 @@ -96,31 +94,29 @@ typedef struct tagEvent { ### 实例描述 -示例中,任务Example_TaskEntry创建一个任务Example_Event,Example_Event读事件阻塞,Example_TaskEntry向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 +示例中,任务ExampleEvent创建一个任务EventReadTask,EventReadTask读事件阻塞,ExampleEvent向该任务写事件。可以通过示例日志中打印的先后顺序理解事件操作时伴随的任务切换。 -1. 在任务Example_TaskEntry创建任务Example_Event,其中任务Example_Event优先级高于Example_TaskEntry。 +1. 在任务ExampleEvent创建任务EventReadTask,其中任务EventReadTask优先级高于ExampleEvent。 -2. 在任务Example_Event中读事件0x00000001,阻塞,发生任务切换,执行任务Example_TaskEntry。 +2. 在任务EventReadTask中读事件0x00000001,阻塞,发生任务切换,执行任务ExampleEvent。 -3. 在任务Example_TaskEntry向任务Example_Event写事件0x00000001,发生任务切换,执行任务Example_Event。 +3. 在任务ExampleEvent写事件0x00000001,发生任务切换,执行任务EventReadTask。 -4. Example_Event得以执行,直到任务结束。 +4. EventReadTask得以执行,直到任务结束。 -5. Example_TaskEntry得以执行,直到任务结束。 +5. ExampleEvent得以执行,直到任务结束。 ### 示例代码 示例代码如下: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleEvent。 + ``` #include "los_event.h" #include "los_task.h" -#include "securec.h" - -/* 任务ID */ -UINT32 g_testTaskId; /* 事件控制结构体 */ EVENT_CB_S g_exampleEvent; @@ -128,8 +124,11 @@ EVENT_CB_S g_exampleEvent; /* 等待的事件类型 */ #define EVENT_WAIT 0x00000001 +/* 等待超时时间 */ +#define EVENT_TIMEOUT 100 + /* 用例任务入口函数 */ -VOID Example_Event(VOID) +VOID EventReadTask(VOID) { UINT32 ret; UINT32 event; @@ -137,39 +136,39 @@ VOID Example_Event(VOID) /* 超时等待方式读事件,超时时间为100 ticks, 若100 ticks后未读取到指定事件,读事件超时,任务直接唤醒 */ printf("Example_Event wait event 0x%x \n", EVENT_WAIT); - event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, 100); + event = LOS_EventRead(&g_exampleEvent, EVENT_WAIT, LOS_WAITMODE_AND, EVENT_TIMEOUT); if (event == EVENT_WAIT) { - printf("Example_Event,read event :0x%x\n", event); + printf("Example_Event, read event :0x%x\n", event); } else { - printf("Example_Event,read event timeout\n"); + printf("Example_Event, read event timeout\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleEvent(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + UINT32 taskId; + TSK_INIT_PARAM_S taskParam = { 0 }; /* 事件初始化 */ ret = LOS_EventInit(&g_exampleEvent); if (ret != LOS_OK) { printf("init event failed .\n"); - return -1; + return LOS_NOK; } /* 创建任务 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Event; - task1.pcName = "EventTsk1"; - task1.uwStackSize = OS_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId, &task1); + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)EventReadTask; + taskParam.pcName = "EventReadTask"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 3; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("task create failed.\n"); return LOS_NOK; } - /* 写g_testTaskId 等待事件 */ + /* 写事件 */ printf("Example_TaskEntry write event.\n"); ret = LOS_EventWrite(&g_exampleEvent, EVENT_WAIT); @@ -183,10 +182,10 @@ UINT32 Example_TaskEntry(VOID) LOS_EventClear(&g_exampleEvent, ~g_exampleEvent.uwEventID); printf("EventMask:%d\n", g_exampleEvent.uwEventID); - /* 删除任务 */ - ret = LOS_TaskDelete(g_testTaskId); + /* 删除事件 */ + ret = LOS_EventDestroy(&g_exampleEvent); if (ret != LOS_OK) { - printf("task delete failed.\n"); + printf("destory event failed .\n"); return LOS_NOK; } @@ -202,9 +201,9 @@ UINT32 Example_TaskEntry(VOID) ``` -Example_Event wait event 0x1 +Example_Event wait event 0x1 Example_TaskEntry write event. -Example_Event,read event :0x1 +Example_Event, read event :0x1 EventMask:1 EventMask:0 ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md index 77b90fb2079a1ea453acde1d4a85ec13270de23e..79fcfd6af0e111bb78184246260a3777afc95d9e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-mutex.md @@ -5,7 +5,7 @@ 互斥锁又称互斥型信号量,是一种特殊的二值性信号量,用于实现对共享资源的独占式处理。 -任意时刻互斥锁的状态只有两种,开锁或闭锁。当有任务持有时,互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放它时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 +任意时刻互斥锁的状态只有两种,开锁或闭锁。当任务持有互斥锁时,该互斥锁处于闭锁状态,这个任务获得该互斥锁的所有权。当该任务释放互斥锁时,该互斥锁被开锁,任务失去该互斥锁的所有权。当一个任务持有互斥锁时,其他任务将不能再对该互斥锁进行开锁或持有。 多任务环境下往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。另外互斥锁可以解决信号量存在的优先级翻转问题。 @@ -24,10 +24,10 @@ **表1** 互斥锁模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁
LOS_MuxDelete:删除指定的互斥锁 | -| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁
LOS_MuxPost:释放指定的互斥锁 | +| 互斥锁的创建和删除 | LOS_MuxCreate:创建互斥锁。
LOS_MuxDelete:删除指定的互斥锁。 | +| 互斥锁的申请和释放 | LOS_MuxPend:申请指定的互斥锁。
LOS_MuxPost:释放指定的互斥锁。 | ## 开发流程 @@ -39,7 +39,7 @@ 2. 申请互斥锁LOS_MuxPend。 申请模式有三种:无阻塞模式、永久阻塞模式、定时阻塞模式。 - - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。 + - 无阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有任务持有,或者持有该互斥锁的任务和申请该互斥锁的任务为同一个任务,则申请成功。否则直接返回并继续运行当前任务,不会产生阻塞。 - 永久阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则,该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,直到有其他任务释放该互斥锁,阻塞任务才会重新得以执行。 - 定时阻塞模式:任务需要申请互斥锁,若该互斥锁当前没有被占用,则申请成功。否则该任务进入阻塞态,系统切换到就绪任务中优先级高者继续执行。任务进入阻塞态后,指定时间超时前有其他任务释放该互斥锁,或者用户指定时间超时后,阻塞任务才会重新得以执行。 @@ -50,7 +50,7 @@ 4. 删除互斥锁LOS_MuxDelete。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 两个任务不能对同一把互斥锁加锁。如果某任务对已被持有的互斥锁加锁,则该任务会被挂起,直到持有该锁的任务对互斥锁解锁,才能执行对这把互斥锁的加锁操作。 +> - 互斥锁支持嵌套,即申请该互斥锁的任务与已经持有该互斥锁的任务为同一个任务时会认为申请成功,按申请次数对应的去释放该锁即可。 > > - 互斥锁不能在中断服务程序中使用。 > @@ -66,67 +66,66 @@ 本实例实现如下流程。 -1. 任务Example_TaskEntry创建一个互斥锁,锁任务调度,创建两个任务Example_MutexTask1、Example_MutexTask2。Example_MutexTask2优先级高于Example_MutexTask1,解锁任务调度。 +1. 任务ExampleMutex创建一个互斥锁,锁任务调度,创建两个任务ExampleMutexTask1、ExampleMutexTask2。ExampleMutexTask2优先级高于ExampleMutexTask1,解锁任务调度。 -2. Example_MutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,Example_MutexTask2挂起,Example_MutexTask1被唤醒。 +2. ExampleMutexTask2被调度,以永久阻塞模式申请互斥锁,并成功获取到该互斥锁,然后任务休眠100Tick,ExampleMutexTask2挂起,ExampleMutexTask1被唤醒。 -3. Example_MutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。10Tick超时时间到达后,Example_MutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被Example_MutexTask2持有,Example_MutexTask1挂起。 +3. ExampleMutexTask1以定时阻塞模式申请互斥锁,等待时间为10Tick,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。10Tick超时时间到达后,ExampleMutexTask1被唤醒,以永久阻塞模式申请互斥锁,因互斥锁仍被ExampleMutexTask2持有,ExampleMutexTask1挂起。 -4. 100Tick休眠时间到达后,Example_MutexTask2被唤醒, 释放互斥锁,唤醒Example_MutexTask1。Example_MutexTask1成功获取到互斥锁后,释放,删除互斥锁。 +4. 100Tick休眠时间到达后,ExampleMutexTask2被唤醒, 释放互斥锁,唤醒ExampleMutexTask1。ExampleMutexTask1成功获取到互斥锁后,释放并删除互斥锁。 ### 示例代码 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleMutex。 + + ``` -#include #include "los_mux.h" -/* 互斥锁句柄id */ +/* 互斥锁句柄 */ UINT32 g_testMux; -/* 任务ID */ -UINT32 g_testTaskId01; -UINT32 g_testTaskId02; -VOID Example_MutexTask1(VOID) +VOID ExampleMutexTask1(VOID) { UINT32 ret; printf("task1 try to get mutex, wait 10 ticks.\n"); /* 申请互斥锁 */ ret = LOS_MuxPend(g_testMux, 10); - if (ret == LOS_OK) { printf("task1 get mutex g_testMux.\n"); - /* 释放互斥锁 */ + /* 释放互斥锁,这个分支正常不应该进来 */ LOS_MuxPost(g_testMux); + LOS_MuxDelete(g_testMux); return; - } + } + if (ret == LOS_ERRNO_MUX_TIMEOUT ) { - printf("task1 timeout and try to get mutex, wait forever.\n"); - /* 申请互斥锁 */ - ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { - printf("task1 wait forever, get mutex g_testMux.\n"); - /* 释放互斥锁 */ - LOS_MuxPost(g_testMux); - /* 删除互斥锁 */ - LOS_MuxDelete(g_testMux); - printf("task1 post and delete mutex g_testMux.\n"); - return; - } + printf("task1 timeout and try to get mutex, wait forever.\n"); + /* 申请互斥锁 */ + ret = LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); + if (ret == LOS_OK) { + printf("task1 wait forever, get mutex g_testMux.\n"); + /* 释放互斥锁 */ + LOS_MuxPost(g_testMux); + /* 删除互斥锁 */ + LOS_MuxDelete(g_testMux); + printf("task1 post and delete mutex g_testMux.\n"); + return; + } } + return; } -VOID Example_MutexTask2(VOID) +VOID ExampleMutexTask2(VOID) { printf("task2 try to get mutex, wait forever.\n"); /* 申请互斥锁 */ (VOID)LOS_MuxPend(g_testMux, LOS_WAIT_FOREVER); - printf("task2 get mutex g_testMux and suspend 100 ticks.\n"); /* 任务休眠100Ticks */ @@ -138,11 +137,13 @@ VOID Example_MutexTask2(VOID) return; } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleMutex(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId01; + UINT32 taskId02; /* 创建互斥锁 */ LOS_MuxCreate(&g_testMux); @@ -151,24 +152,22 @@ UINT32 Example_TaskEntry(VOID) LOS_TaskLock(); /* 创建任务1 */ - memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask1; + task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask1; task1.pcName = "MutexTsk1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + ret = LOS_TaskCreate(&taskId01, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - memset(&task2, 0, sizeof(TSK_INIT_PARAM_S)); - task2.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_MutexTask2; + task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleMutexTask2; task2.pcName = "MutexTsk2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; task2.usTaskPrio = 4; - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + ret = LOS_TaskCreate(&taskId02, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -185,7 +184,7 @@ UINT32 Example_TaskEntry(VOID) ### 结果验证 编译运行得到的结果为: - + ``` task2 try to get mutex, wait forever. task2 get mutex g_testMux and suspend 100 ticks. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md index 16178ecadabea0217f49780744c8d272bc39d590..f2e60ebd8b30ea049f5238dbd1ae52bc17e40ec9 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-queue.md @@ -3,7 +3,7 @@ ## 基本概念 -队列又称消息队列,是一种常用于任务间通信的数据结构。队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 +消息队列又称队列,是一种任务间通信的机制。消息队列接收来自任务或中断的不固定长度消息,并根据不同的接口确定传递的消息是否存放在队列空间中。 任务能够从队列里面读取消息,当队列中的消息为空时,挂起读取任务;当队列中有新消息时,挂起的读取任务被唤醒并处理新消息。任务也能够往队列里写入消息,当队列已经写满消息时,挂起写入任务;当队列中有空闲消息节点时,挂起的写入任务被唤醒并写入消息。 @@ -12,44 +12,40 @@ 消息队列提供了异步处理机制,允许将一个消息放入队列,但不立即处理。同时队列还有缓冲消息的作用,可以使用队列实现任务异步通信,队列具有如下特性: - 消息以先进先出的方式排队,支持异步读写。 - - 读队列和写队列都支持超时机制。 - - 每读取一条消息,就会将该消息节点设置为空闲。 - - 发送消息类型由通信双方约定,可以允许不同长度(不超过队列的消息节点大小)的消息。 - - 一个任务能够从任意一个消息队列接收和发送消息。 - - 多个任务能够从同一个消息队列接收和发送消息。 - -- 创建队列时所需的队列空间,接口内系统自行动态申请内存。 +- 创建普通队列时所需的队列空间,由系统自行动态申请内存。 +- 创建静态队列时所需的队列空间,由用户传入。这块空间在队列删除之后也由用户去释放。 ## 运行机制 - ### 队列控制块 - +队列会在初始化时给分配一个属于自己的控制块,控制块包含了队列的名称、状态等信息。删除队列时会释放该控制块。 + +队列控制块数据结构如下: + + ``` -/** - * 队列控制块数据结构 - */ typedef struct { - UINT8 *queue; /* 队列消息内存空间的指针 */ - UINT16 queueState; /* 队列状态 */ - UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ - UINT16 queueSize; /* 消息节点大小 */ - UINT16 queueID; /* 队列ID */ - UINT16 queueHead; /* 消息头节点位置(数组下标)*/ - UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ - UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, - 数组下标1的元素表示队列中可写消息数 */ - LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, - 下标0:读取链表,下标1:写入链表 */ - LOS_DL_LIST memList; /* 内存块链表 */ + UINT8 *queue; /* 队列消息内存空间的指针 */ + UINT8 *queueName /* 队列名称 */ + UINT16 queueState; /* 队列状态 */ + UINT16 queueLen; /* 队列中消息节点个数,即队列长度 */ + UINT16 queueSize; /* 消息节点大小 */ + UINT16 queueID; /* 队列ID */ + UINT16 queueHead; /* 消息头节点位置(数组下标)*/ + UINT16 queueTail; /* 消息尾节点位置(数组下标)*/ + UINT16 readWriteableCnt[OS_READWRITE_LEN]; /* 数组下标0的元素表示队列中可读消息数, + 数组下标1的元素表示队列中可写消息数 */ + LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /* 读取或写入消息的任务等待链表, + 下标0:读取链表,下标1:写入链表 */ + LOS_DL_LIST memList; /* 内存块链表 */ } LosQueueCB; ``` @@ -81,12 +77,12 @@ typedef struct ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除消息队列 | - LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
- LOS_QueueDelete:根据队列ID删除一个指定队列。 | -| 读/写队列(不带拷贝) | - LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
- LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
- LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | -| 读/写队列(带拷贝) | - LOS_QueueReadCopy:读取指定队列头节点中的数据。
- LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
- LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | -| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | +| 创建/删除消息队列 |  LOS_QueueCreate:创建一个消息队列,由系统动态申请队列空间。
LOS_QueueCreateStatic:创建一个消息队列,由用户传入队列空间。
 LOS_QueueDelete:根据队列ID删除一个指定队列,静态消息队列删除后,队列空间需要用例自行处理。 | +| 读/写队列(不带拷贝) |  LOS_QueueRead:读取指定队列头节点中的数据(队列节点中的数据实际上是一个地址)。
 LOS_QueueWrite:向指定队列尾节点中写入入参bufferAddr的值(即buffer的地址)。
 LOS_QueueWriteHead:向指定队列头节点中写入入参bufferAddr的值(即buffer的地址)。 | +| 读/写队列(带拷贝) |  LOS_QueueReadCopy:读取指定队列头节点中的数据。
 LOS_QueueWriteCopy:向指定队列尾节点中写入入参bufferAddr中保存的数据。
 LOS_QueueWriteHeadCopy:向指定队列头节点中写入入参bufferAddr中保存的数据。 | +| 获取队列信息 | LOS_QueueInfoGet:获取指定队列的信息,包括队列ID、队列长度、消息节点大小、头节点、尾节点、可读节点数量、可写节点数量、等待读操作的任务、等待写操作的任务。 | ## 开发流程 @@ -140,11 +136,14 @@ typedef struct 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleQueue。 + + ``` #include "los_task.h" #include "los_queue.h" -static UINT32 g_queue; + +STATIC UINT32 g_queue; #define BUFFER_LEN 50 VOID SendEntry(VOID) @@ -154,7 +153,7 @@ VOID SendEntry(VOID) UINT32 len = sizeof(abuf); ret = LOS_QueueWriteCopy(g_queue, abuf, len, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("send message failure, error: %x\n", ret); } } @@ -165,17 +164,17 @@ VOID RecvEntry(VOID) CHAR readBuf[BUFFER_LEN] = {0}; UINT32 readLen = BUFFER_LEN; - //休眠1s + /* 休眠1s */ usleep(1000000); ret = LOS_QueueReadCopy(g_queue, readBuf, &readLen, 0); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("recv message failure, error: %x\n", ret); } - printf("recv message: %s\n", readBuf); + printf("recv message: %s.\n", readBuf); ret = LOS_QueueDelete(g_queue); - if(ret != LOS_OK) { + if (ret != LOS_OK) { printf("delete the queue failure, error: %x\n", ret); } @@ -186,25 +185,28 @@ UINT32 ExampleQueue(VOID) { printf("start queue example.\n"); UINT32 ret = 0; - UINT32 task1, task2; - TSK_INIT_PARAM_S initParam = {0}; - - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; - initParam.usTaskPrio = 9; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.pcName = "SendQueue"; + UINT32 task1; + UINT32 task2; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; LOS_TaskLock(); - ret = LOS_TaskCreate(&task1, &initParam); + + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)SendEntry; + taskParam1.usTaskPrio = 9; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.pcName = "SendQueue"; + ret = LOS_TaskCreate(&task1, &taskParam1); if(ret != LOS_OK) { printf("create task1 failed, error: %x\n", ret); return ret; } - initParam.pcName = "RecvQueue"; - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; - initParam.usTaskPrio = 10; - ret = LOS_TaskCreate(&task2, &initParam); + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)RecvEntry; + taskParam2.usTaskPrio = 10; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pcName = "RecvQueue"; + ret = LOS_TaskCreate(&task2, &taskParam2); if(ret != LOS_OK) { printf("create task2 failed, error: %x\n", ret); return ret; @@ -227,7 +229,7 @@ UINT32 ExampleQueue(VOID) 编译运行得到的结果为: - + ``` start queue example. create the queue success. diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md index 2fb49adb65c17d90504ac54465011f5099760734..b8451b04faa305154792a40778388031158a2e63 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-sem.md @@ -11,7 +11,7 @@ - 正值,表示该信号量当前可被获取。 -以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: +信号量可用于同步或者互斥。以同步为目的的信号量和以互斥为目的的信号量在使用上有如下不同: - 用作互斥时,初始信号量计数值不为0,表示可用的共享资源个数。在需要使用共享资源前,先获取信号量,然后使用一个共享资源,使用完毕后释放信号量。这样在共享资源被取完,即信号量计数减至0时,其他需要获取信号量的任务将被阻塞,从而保证了共享资源的互斥访问。另外,当共享资源数为1时,建议使用二值信号量,一种类似于互斥锁的机制。 @@ -23,7 +23,7 @@ ### 信号量控制块 - + ``` /** * 信号量控制块数据结构 @@ -40,7 +40,7 @@ typedef struct { ### 信号量运作原理 -信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 +信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,通过LOSCFG_BASE_IPC_SEM_LIMIT宏实现,按产品实际需要设定),并把所有信号量初始化成未使用,加入到未使用链表中供系统使用。 信号量创建,从未使用的信号量链表中获取一个信号量,并设定初值。 @@ -58,10 +58,10 @@ typedef struct { ## 接口说明 - | 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建/删除信号量 | - LOS_SemCreate:创建信号量,返回信号量ID
- LOS_BinarySemCreate:创建二值信号量,其计数值最大为1
- LOS_SemDelete:删除指定的信号量 | -| 申请/释放信号量 | - LOS_SemPend:申请指定的信号量,并设置超时时间
- LOS_SemPost:释放指定的信号量 | +| 创建/删除信号量 |  LOS_SemCreate:创建信号量,返回信号量ID。
 LOS_BinarySemCreate:创建二值信号量,其计数值最大为1。
 LOS_SemDelete:删除指定的信号量。 | +| 申请/释放信号量 |  LOS_SemPend:申请指定的信号量,并设置超时时间。
 LOS_SemPost:释放指定的信号量。 | ## 开发流程 @@ -101,17 +101,11 @@ typedef struct { 示例代码如下: - -``` -#include "los_sem.h" -#include "securec.h" +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSem。 -/* 任务ID */ -static UINT32 g_testTaskId01; -static UINT32 g_testTaskId02; -/* 测试任务优先级 */ -#define TASK_PRIO_TEST 5 +``` +#include "los_sem.h" /* 信号量结构体id */ static UINT32 g_semId; @@ -121,19 +115,17 @@ VOID ExampleSemTask1(VOID) UINT32 ret; printf("ExampleSemTask1 try get sem g_semId, timeout 10 ticks.\n"); - /* 定时阻塞模式申请信号量,定时时间为10ticks */ ret = LOS_SemPend(g_semId, 10); - /* 申请到信号量 */ if (ret == LOS_OK) { LOS_SemPost(g_semId); return; } + /* 定时时间到,未申请到信号量 */ if (ret == LOS_ERRNO_SEM_TIMEOUT) { printf("ExampleSemTask1 timeout and try get sem g_semId wait forever.\n"); - /*永久阻塞模式申请信号量*/ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); printf("ExampleSemTask1 wait_forever and get sem g_semId.\n"); @@ -151,15 +143,14 @@ VOID ExampleSemTask2(VOID) /* 永久阻塞模式申请信号量 */ ret = LOS_SemPend(g_semId, LOS_WAIT_FOREVER); - if (ret == LOS_OK) { printf("ExampleSemTask2 get sem g_semId and then delay 20 ticks.\n"); } /* 任务休眠20 ticks */ LOS_TaskDelay(20); - printf("ExampleSemTask2 post sem g_semId.\n"); + /* 释放信号量 */ LOS_SemPost(g_semId); return; @@ -168,8 +159,10 @@ VOID ExampleSemTask2(VOID) UINT32 ExampleSem(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; - TSK_INIT_PARAM_S task2; + TSK_INIT_PARAM_S task1 = { 0 }; + TSK_INIT_PARAM_S task2 = { 0 }; + UINT32 taskId1; + UINT32 taskId2; /* 创建信号量 */ LOS_SemCreate(0, &g_semId); @@ -178,24 +171,22 @@ UINT32 ExampleSem(VOID) LOS_TaskLock(); /* 创建任务1 */ - (VOID)memset_s(&task1, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask1; task1.pcName = "TestTask1"; task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = TASK_PRIO_TEST; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + task1.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId1, &task1); if (ret != LOS_OK) { printf("task1 create failed.\n"); return LOS_NOK; } /* 创建任务2 */ - (VOID)memset_s(&task2, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); task2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleSemTask2; task2.pcName = "TestTask2"; task2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task2.usTaskPrio = (TASK_PRIO_TEST - 1); - ret = LOS_TaskCreate(&g_testTaskId02, &task2); + task2.usTaskPrio = 4; + ret = LOS_TaskCreate(&taskId2, &task2); if (ret != LOS_OK) { printf("task2 create failed.\n"); return LOS_NOK; @@ -221,12 +212,11 @@ UINT32 ExampleSem(VOID) 编译运行得到的结果为: - + ``` ExampleSemTask2 try get sem g_semId wait forever. -ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 try get sem g_semId, timeout 10 ticks. - +ExampleSemTask2 get sem g_semId and then delay 20 ticks. ExampleSemTask1 timeout and try get sem g_semId wait forever. ExampleSemTask2 post sem g_semId. ExampleSemTask1 wait_forever and get sem g_semId. diff --git a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md similarity index 58% rename from zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-list.md index f0c0d1cbea02488cccc34c8959d348ef15ad7ed5..ec6ae58a9befafbe9cc7868871003073c1702f80 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-appx-data-list.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-list.md @@ -12,16 +12,16 @@ 双向链表模块为用户提供下面几种功能,接口详细信息可以查看API参考。 - | | | +| | | | -------- | -------- | -| **功能分类** | **接口描述** | -| 初始化链表 | - LOS_ListInit:将指定双向链表节点初始化为双向链表
- LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表 | -| 增加节点 | - LOS_ListAdd:将指定节点插入到双向链表头端
- LOS_ListTailInsert:将指定节点插入到双向链表尾端 | -| 删除节点 | - LOS_ListDelete:将指定节点从链表中删除
- LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | -| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空 | -| 获取结构体信息 | - LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量 | -| 遍历双向链表 | - LOS_DL_LIST_FOR_EACH:遍历双向链表
- LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | -| 遍历包含双向链表的结构体 | - LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址
- LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | +| **功能分类** | **接口描述** | +| 初始化和删除链表 |  LOS_ListInit:将指定双向链表节点初始化为双向链表。
 LOS_DL_LIST_HEAD:定义一个双向链表节点并以该节点初始化为双向链表。
LOS_ListDelInit:删除指定的双向链表。 | +| 增加节点 |  LOS_ListAdd:将指定节点插入到双向链表头端。
 LOS_ListTailInsert:将指定节点插入到双向链表尾端。 | +| 删除节点 |  LOS_ListDelete:将指定节点从链表中删除。
 LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表。 | +| 判断双向链表是否为空 | LOS_ListEmpty:判断链表是否为空。 | +| 获取结构体信息 |  LOS_DL_LIST_ENTRY:获取包含链表的结构体地址,接口的第一个入参表示的是链表中的某个节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。
 LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量。 | +| 遍历双向链表 |  LOS_DL_LIST_FOR_EACH:遍历双向链表。
 LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验。 | +| 遍历包含双向链表的结构体 |  LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址。
 LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址。 | ## 开发流程 @@ -69,22 +69,24 @@ 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleList。 + + ``` #include "stdio.h" #include "los_list.h" -static UINT32 ListSample(VOID) +STATIC UINT32 ExampleList(VOID) { LOS_DL_LIST listHead = {NULL,NULL}; LOS_DL_LIST listNode1 = {NULL,NULL}; LOS_DL_LIST listNode2 = {NULL,NULL}; - //首先初始化链表 + /* 初始化链表 */ printf("Initial head\n"); LOS_ListInit(&listHead); - //添加节点1和节点2,并校验他们的相互关系 + /* 添加节点1和节点2,并校验他们的相互关系 */ LOS_ListAdd(&listHead, &listNode1); if (listNode1.pstNext == &listHead && listNode1.pstPrev == &listHead) { printf("Add listNode1 success\n"); @@ -95,11 +97,11 @@ static UINT32 ListSample(VOID) printf("Tail insert listNode2 success\n"); } - //删除两个节点 + /* 删除两个节点 */ LOS_ListDelete(&listNode1); LOS_ListDelete(&listNode2); - //确认链表为空 + /* 确认链表为空 */ if (LOS_ListEmpty(&listHead)) { printf("Delete success\n"); } @@ -113,7 +115,7 @@ static UINT32 ListSample(VOID) 编译运行得到的结果为: - + ``` Initial head Add listNode1 success diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md index 5071ddf325680c7d939907b5bb2fd8d8f1368e77..a95eb894ce9723b9ae74c39efd8e23fd6e87263e 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md @@ -45,12 +45,12 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 **表1** 静态内存模块接口 -| 功能分类 | 接口名 | +| 功能分类 | 接口名 | | -------- | -------- | -| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | -| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | -| 申请、释放静态内存 | - LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
- LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | -| 获取、打印静态内存池信息 | - LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
- LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | +| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | +| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | +| 申请、释放静态内存 |  LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
 LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | +| 获取、打印静态内存池信息 |  LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
 LOS_ShowBox:打印指定静态内存池所有节点信息,打印等级是LOG_INFO_LEVEL(当前打印等级配置是PRINT_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。 @@ -91,21 +91,26 @@ OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接 6. 释放该内存块。 示例代码如下: + + 本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleStaticMem。 + - ``` #include "los_membox.h" -VOID Example_StaticMem(VOID) +#define MEMBOX_POOL_SIZE 100 +#define MEMBOX_BLOCK_SZIE 10 +#define MEMBOX_WR_TEST_NUM 828 +VOID ExampleStaticMem(VOID) { UINT32 *mem = NULL; - UINT32 blkSize = 10; - UINT32 boxSize = 100; - UINT32 boxMem[1000]; + UINT32 blkSize = MEMBOX_BLOCK_SZIE; + UINT32 poolSize = MEMBOX_POOL_SIZE; + UINT32 boxMem[MEMBOX_POOL_SIZE]; UINT32 ret; - /*内存池初始化*/ - ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize); + /* 内存池初始化 */ + ret = LOS_MemboxInit(&boxMem[0], poolSize, blkSize); if(ret != LOS_OK) { printf("Membox init failed!\n"); return; @@ -113,23 +118,23 @@ VOID Example_StaticMem(VOID) printf("Membox init success!\n"); } - /*申请内存块*/ + /* 申请内存块 */ mem = (UINT32 *)LOS_MemboxAlloc(boxMem); - if (NULL == mem) { + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*清除内存内容*/ + /* 清除内存内容 */ LOS_MemboxClr(boxMem, mem); - printf("Mem clear success \n *mem = %d\n", *mem); + printf("Mem clear success \n*mem = %d\n", *mem); - /*释放内存*/ + /* 释放内存 */ ret = LOS_MemboxFree(boxMem, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); @@ -139,6 +144,7 @@ VOID Example_StaticMem(VOID) return; } + ``` @@ -146,7 +152,7 @@ VOID Example_StaticMem(VOID) 输出结果如下: - + ``` Membox init success! Mem alloc success! @@ -197,7 +203,7 @@ OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分 2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。 -3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE。 +3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize + OS_MEM_NODE_HEAD_SIZE(即sizeof(struct OsMemUsedNodeHead))。 4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。 @@ -218,14 +224,14 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 **表1** 动态内存模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 初始化和删除内存池 | - LOS_MemInit:初始化一块指定的动态内存池,大小为size。
- LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 申请、释放动态内存 | - LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
- LOS_MemFree:释放从指定动态内存中申请的内存。
- LOS_MemRealloc:释放从指定动态内存中申请的内存。 | -| 获取内存池信息 | - LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
- LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
- LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
- LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 | -| 获取内存块信息 | - LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
- LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | -| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | -| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | +| 初始化和删除内存池 |  LOS_MemInit:初始化一块指定的动态内存池,大小为size。
 LOS_MemDeInit:删除指定内存池,仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 申请、释放动态内存 |  LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
 LOS_MemFree:释放从指定动态内存中申请的内存。
 LOS_MemRealloc:释放从指定动态内存中申请的内存。 | +| 获取内存池信息 |  LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
 LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
 LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
 LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开编译控制开关LOSCFG_MEM_MUL_POOL时有效。 | +| 获取内存块信息 |  LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
 LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | +| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开编译控制开关LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | +| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。 @@ -265,18 +271,24 @@ OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接 示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleDynMem。 + + ``` #include "los_memory.h" + #define TEST_POOL_SIZE (2*1024) -__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE]; -VOID Example_DynMem(VOID) +#define MEMBOX_WR_TEST_NUM 828 + +__attribute__((aligned(4))) UINT8 g_testDynPool[TEST_POOL_SIZE]; + +VOID ExampleDynMem(VOID) { UINT32 *mem = NULL; UINT32 ret; - /*初始化内存池*/ - ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE); + /* 初始化内存池 */ + ret = LOS_MemInit(g_testDynPool, TEST_POOL_SIZE); if (LOS_OK == ret) { printf("Mem init success!\n"); } else { @@ -284,20 +296,20 @@ VOID Example_DynMem(VOID) return; } - /*分配内存*/ - mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4); - if (NULL == mem) { + /* 申请内存块 */ + mem = (UINT32 *)LOS_MemAlloc(g_testDynPool, 4); + if (mem == NULL) { printf("Mem alloc failed!\n"); return; } printf("Mem alloc success!\n"); - /*赋值*/ - *mem = 828; + /* 内存地址读写验证 */ + *mem = MEMBOX_WR_TEST_NUM; printf("*mem = %d\n", *mem); - /*释放内存*/ - ret = LOS_MemFree(g_testPool, mem); + /* 释放内存 */ + ret = LOS_MemFree(g_testDynPool, mem); if (LOS_OK == ret) { printf("Mem free success!\n"); } else { @@ -313,7 +325,7 @@ VOID Example_DynMem(VOID) 输出结果如下: - + ``` Mem init success! Mem alloc success! diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md index 01a3b8f011e35538fe15839b3c7b79cc017f3f53..7fddc4be0328b6c55b42c32e254d1ae242598f70 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-soft.md @@ -24,7 +24,7 @@ ## 运行机制 -软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置。 +软件定时器是系统资源,在模块初始化的时候已经分配了一块连续的内存,系统支持的最大定时器个数由los_config.h中的LOSCFG_BASE_CORE_SWTMR_LIMIT宏配置,该值按产品实际需要设定。 软件定时器使用了系统的一个队列和一个任务资源,软件定时器的触发遵循队列规则,先进先出。定时时间短的定时器总是比定时时间长的靠近队列头,满足优先被触发的准则。 @@ -64,11 +64,11 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 **表1** 软件定时器接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器
- LOS_SwtmrDelete:删除定时器 | -| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器
- LOS_SwtmrStop:停止定时器 | -| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数 | +| 创建、删除定时器 | - LOS_SwtmrCreate:创建定时器。
- LOS_SwtmrDelete:删除定时器。 | +| 启动、停止定时器 | - LOS_SwtmrStart:启动定时器。
- LOS_SwtmrStop:停止定时器。 | +| 获得软件定时器剩余Tick数 | LOS_SwtmrTimeGet:获得软件定时器剩余Tick数。 | ## 开发流程 @@ -130,86 +130,107 @@ OpenHarmony LiteOS-M内核的软件定时器模块提供下面几种功能,接 代码实现如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleSwtmr。 + + ``` #include "los_swtmr.h" -/* Timer count */ -UINT32 g_timerCount1 = 0; -UINT32 g_timerCount2 = 0; +/* 定时器间隔时间 */ +#define SWTMR_INTERVAL_LONG 1000 +#define SWTMR_INTERVAL_SHORT 100 -/* 任务ID */ -UINT32 g_testTaskId01; +/* 定时器触发次数计数 */ +UINT32 g_timerCount1 = 0; +UINT32 g_timerCount2 = 0; -void Timer1_Callback(UINT32 arg) // 回调函数1 +/* 回调函数1,单次触发定时器的回调函数 */ +void Timer1Callback(UINT32 arg) { - UINT32 tick_last1; g_timerCount1++; - tick_last1 = (UINT32)LOS_TickCountGet(); // 获取当前Tick数 - printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1); -} + printf("g_timerCount1=%d\n", g_timerCount1); +} -void Timer2_Callback(UINT32 arg) // 回调函数2 +/* 回调函数2,多次触发定时器的回调函数 */ +void Timer2Callback(UINT32 arg) { - UINT32 tick_last2; - tick_last2 = (UINT32)LOS_TickCountGet(); g_timerCount2++; - printf("g_timerCount2=%d tick_last2=%d\n", g_timerCount2, tick_last2); -} + printf("g_timerCount2=%d\n", g_timerCount2); +} -void Timer_example(void) +void SwtmrTest(void) { UINT32 ret; - UINT32 id1; // timer id1 - UINT32 id2; // timer id2 + UINT32 id1; // 定时器id1,单次触发定时器 + UINT32 id2; // 定时器id2,周期触发定时器 UINT32 tickCount; - /*创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ - LOS_SwtmrCreate(1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1); +#if (LOSCFG_BASE_CORE_SWTMR_ALIGN == 1) + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); - /*创建周期性软件定时器,每100Tick数执行回调函数2 */ - LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1); - printf("create Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0, + OS_SWTMR_ROUSES_IGNORE, OS_SWTMR_ALIGN_SENSITIVE); +#else + /* 创建单次软件定时器,Tick数为1000,启动到1000Tick数时执行回调函数1 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_LONG, LOS_SWTMR_MODE_ONCE, Timer1Callback, &id1, 0); - LOS_SwtmrStart(id1); //启动单次软件定时器 - printf("start Timer1 success\n"); + /* 创建周期性软件定时器,每100Tick数执行回调函数2 */ + LOS_SwtmrCreate(SWTMR_INTERVAL_SHORT, LOS_SWTMR_MODE_PERIOD, Timer2Callback, &id2, 0); +#endif - LOS_TaskDelay(200); //延时200Tick数 - LOS_SwtmrTimeGet(id1, &tickCount); // 获得单次软件定时器剩余Tick数 - printf("tickCount=%d\n", tickCount); + /* 启动单次软件定时器 */ + ret = LOS_SwtmrStart(id1); + printf("start Timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStop(id1); // 停止软件定时器 - printf("stop Timer1 success\n"); + /* 短时间延时,定时器还未触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_SHORT); + + /* 单次定时器还未到时间触发,此时停止应该成功 */ + ret = LOS_SwtmrStop(id1); + printf("stop timer1 %s\n", (ret == LOS_OK) ? "success" : "failed"); LOS_SwtmrStart(id1); - LOS_TaskDelay(1000); + + /* 长时间延时,定时器触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); + + /* 单次定时器触发后自删除,此时停止失败才是正常 */ + ret = LOS_SwtmrStop(id1); + printf("timer1 self delete test %s\n", (ret != LOS_OK) ? "success" : "failed"); + + /* 启动周期性软件定时器 */ + ret = LOS_SwtmrStart(id2); + printf("start Timer2 %s\n", (ret == LOS_OK) ? "success" : "failed"); - LOS_SwtmrStart(id2); // 启动周期性软件定时器 - printf("start Timer2\n"); + /* 长时间延时,定时器周期触发 */ + LOS_TaskDelay(SWTMR_INTERVAL_LONG); - LOS_TaskDelay(1000); LOS_SwtmrStop(id2); - ret = LOS_SwtmrDelete(id2); // 删除软件定时器 + + ret = LOS_SwtmrDelete(id2); if (ret == LOS_OK) { printf("delete Timer2 success\n"); } } -UINT32 Example_TaskEntry(VOID) +UINT32 ExampleSwtmr(VOID) { UINT32 ret; - TSK_INIT_PARAM_S task1; + TSK_INIT_PARAM_S taskParam = { 0 }; + UINT32 taskId; /* 锁任务调度 */ LOS_TaskLock(); - /* 创建任务1 */ - (VOID)memset(&task1, 0, sizeof(TSK_INIT_PARAM_S)); - task1.pfnTaskEntry = (TSK_ENTRY_FUNC)Timer_example; - task1.pcName = "TimerTsk"; - task1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - task1.usTaskPrio = 5; - ret = LOS_TaskCreate(&g_testTaskId01, &task1); + /* 创建任务 */ + taskParam.pfnTaskEntry = (TSK_ENTRY_FUNC)SwtmrTest; + taskParam.pcName = "TimerTsk"; + taskParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam.usTaskPrio = 5; + ret = LOS_TaskCreate(&taskId, &taskParam); if (ret != LOS_OK) { printf("TimerTsk create failed.\n"); return LOS_NOK; @@ -217,7 +238,6 @@ UINT32 Example_TaskEntry(VOID) /* 解锁任务调度 */ LOS_TaskUnlock(); - return LOS_OK; } ``` @@ -227,24 +247,22 @@ UINT32 Example_TaskEntry(VOID) 编译烧录运行,输出结果如下: - + ``` -create Timer1 success start Timer1 success -tickCount=798 -stop Timer1 success -g_timerCount1=1, tick_last1=1208 -delete Timer1 success -start Timer2 -g_timerCount2=1 tick_last2=1313 -g_timerCount2=2 tick_last2=1413 -g_timerCount2=3 tick_last2=1513 -g_timerCount2=4 tick_last2=1613 -g_timerCount2=5 tick_last2=1713 -g_timerCount2=6 tick_last2=1813 -g_timerCount2=7 tick_last2=1913 -g_timerCount2=8 tick_last2=2013 -g_timerCount2=9 tick_last2=2113 -g_timerCount2=10 tick_last2=2213 +stop timer1 success +g_timerCount1=1 +timer1 self delete test success +start Timer2 success +g_timerCount2=1 +g_timerCount2=2 +g_timerCount2=3 +g_timerCount2=4 +g_timerCount2=5 +g_timerCount2=6 +g_timerCount2=7 +g_timerCount2=8 +g_timerCount2=9 +g_timerCount2=10 delete Timer2 success ``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md index 50d320e915b4262a137e2cc89e92c7d387d79861..bf246040a71e2b7b17e049126e4339292c706f25 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-task.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-task.md @@ -3,7 +3,7 @@ ## 基本概念 -从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,并独立于其它任务运行。 +从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,各任务的运行相互独立。 OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。任务模块具有如下特性: @@ -40,7 +40,9 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 ![zh-cn_image_0000001200612002](figures/zh-cn_image_0000001200612002.png) -**任务状态迁移说明:** +系统会同时存在多个任务,因此就绪态和阻塞态的任务分别会加入就绪队列和阻塞队列。队列只是相同状态任务的合集,加入队列的先后与任务状态迁移的顺序无关。运行态任务仅存在一个,不存在运行态队列。 + +**任务状态迁移说明** - 就绪态→运行态 任务创建后进入就绪态,发生任务切换时,就绪队列中最高优先级的任务被执行,从而进入运行态,同时该任务从就绪队列中移出。 @@ -48,11 +50,11 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 - 运行态→阻塞态 正在运行的任务发生阻塞(挂起、延时、读信号量等)时,将该任务插入到对应的阻塞队列中,任务状态由运行态变成阻塞态,然后发生任务切换,运行就绪队列中最高优先级任务。 -- 阻塞态→就绪态(阻塞态→运行态) +- 阻塞态→就绪态(阻塞态→运行态的前置条件) 阻塞的任务被恢复后(任务恢复、延时时间超时、读信号量超时或读到信号量等),此时被恢复的任务会被加入就绪队列,从而由阻塞态变成就绪态;此时如果被恢复任务的优先级高于正在运行任务的优先级,则会发生任务切换,该任务由就绪态变成运行态。 - 就绪态→阻塞态 - 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中删除,不会参与任务调度,直到该任务被恢复。 + 任务也有可能在就绪态时被阻塞(挂起),此时任务状态由就绪态变为阻塞态,该任务从就绪队列中移出,不会参与任务调度,直到该任务被恢复。 - 运行态→就绪态 有更高优先级任务创建或者恢复后,会发生任务调度,此刻就绪队列中最高优先级任务变为运行态,那么原先运行的任务由运行态变为就绪态,依然在就绪队列中。 @@ -65,7 +67,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 **任务ID** -任务ID,在任务创建时通过参数返回给用户,是任务的重要标识。系统中的ID号是唯一的。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 +在任务创建时通过参数返回给用户。系统中任务ID号是唯一的,是任务的重要标识。用户可以通过任务ID对指定任务进行任务挂起、任务恢复、查询任务名等操作。 **任务优先级** @@ -83,7 +85,7 @@ OpenHarmony LiteOS-M的任务模块可以给用户提供多个任务,实现任 任务在运行过程中使用的一些资源,如寄存器等,称为任务上下文。当这个任务挂起时,其他任务继续执行,可能会修改寄存器等资源中的值。如果任务切换时没有保存任务上下文,可能会导致任务恢复后出现未知错误。因此在任务切换时会将切出任务的任务上下文信息,保存在自身的任务栈中,以便任务恢复后,从栈空间中恢复挂起时的上下文信息,从而继续执行挂起时被打断的代码。 -**任务控制块TCB** +**任务控制块(TCB)** 每个任务都含有一个任务控制块(TCB)。TCB包含了任务上下文栈指针(stack pointer)、任务状态、任务优先级、任务ID、任务名、任务栈大小等信息。TCB可以反映出每个任务运行情况。 @@ -103,15 +105,14 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 **表1** 任务管理模块接口 -| 功能分类 | 接口描述 | +| 功能分类 | 接口描述 | | -------- | -------- | -| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | -| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:传入参数为毫秒数,转换为Tick数目,调用LOS_TaskDelay。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | -| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | -| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | -| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | -| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启宏LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | - +| 创建和删除任务 | LOS_TaskCreateOnly:创建任务,并使该任务进入suspend状态。
LOS_TaskCreate:创建任务,并使该任务进入ready状态,如果就绪队列中没有更高优先级的任务,则运行该任务。
LOS_TaskDelete:删除指定的任务。 | +| 控制任务状态 | LOS_TaskResume:恢复挂起的任务,使该任务进入ready状态。
LOS_TaskSuspend:挂起指定的任务,然后切换任务。
LOS_TaskJoin:挂起当前任务,等待指定任务运行结束并回收其任务控制块资源
LOS_TaskDelay:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为Tick数目。
LOS_Msleep:任务延时等待,释放CPU,等待时间到期后该任务会重新进入ready状态。传入参数为毫秒数。
LOS_TaskYield:当前任务时间片设置为0,释放CPU,触发调度运行就绪任务队列中优先级最高的任务。 | +| 控制任务调度 | LOS_TaskLock:锁任务调度,但任务仍可被中断打断。
LOS_TaskUnlock:解锁任务调度。
LOS_Schedule:触发任务调度。 | +| 控制任务优先级 | LOS_CurTaskPriSet:设置当前任务的优先级。
LOS_TaskPriSet:设置指定任务的优先级。
LOS_TaskPriGet:获取指定任务的优先级。 | +| 获取任务信息 | LOS_CurTaskIDGet:获取当前任务的ID。
LOS_NextTaskIDGet:获取任务就绪队列中优先级最高的任务的ID。
LOS_NewTaskIDGet:等同LOS_NextTaskIDGet。
LOS_CurTaskNameGet:获取当前任务的名称。
LOS_TaskNameGet:获取指定任务的名称。
LOS_TaskStatusGet:获取指定任务的状态。
LOS_TaskInfoGet:获取指定任务的信息,包括任务状态、优先级、任务栈大小、栈顶指针SP、任务入口函数、已使用的任务栈大小等。
LOS_TaskIsRunning:获取任务模块是否已经开始调度运行。 | +| 任务信息维测 | LOS_TaskSwitchInfoGet:获取任务切换信息,需要开启编译控制宏:LOSCFG_BASE_CORE_EXC_TSK_SWITCH。 | ## 开发流程 @@ -161,20 +162,24 @@ OpenHarmony LiteOS-M内核的任务管理模块提供下面几种功能,接口 本实例介绍基本的任务操作方法,包含2个不同优先级任务的创建、任务延时、任务锁与解锁调度、挂起和恢复等操作,阐述任务优先级调度的机制以及各接口的应用。示例代码如下: - +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTask。 + + ``` +#include "los_task.h" + UINT32 g_taskHiId; UINT32 g_taskLoId; -#define TSK_PRIOR_HI 4 -#define TSK_PRIOR_LO 5 +#define TSK_PRIOR_HI 3 /* 高优先级任务的优先级 */ +#define TSK_PRIOR_LO 4 /* 低优先级任务的优先级 */ -UINT32 Example_TaskHi(VOID) +UINT32 ExampleTaskHi(VOID) { UINT32 ret; printf("Enter TaskHi Handler.\n"); - /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(TaskLo任务) */ + /* 延时100个Ticks,延时后该任务会挂起,执行剩余任务中最高优先级的任务(即TaskLo任务) */ ret = LOS_TaskDelay(100); if (ret != LOS_OK) { printf("Delay TaskHi Failed.\n"); @@ -195,7 +200,7 @@ UINT32 Example_TaskHi(VOID) } /* 低优先级任务入口函数 */ -UINT32 Example_TaskLo(VOID) +UINT32 ExampleTaskLo(VOID) { UINT32 ret; @@ -220,24 +225,25 @@ UINT32 Example_TaskLo(VOID) } /* 任务测试入口函数,创建两个不同优先级的任务 */ -UINT32 Example_TskCaseEntry(VOID) +UINT32 ExampleTask(VOID) { UINT32 ret; - TSK_INIT_PARAM_S initParam; + TSK_INIT_PARAM_S taskParam1 = { 0 }; + TSK_INIT_PARAM_S taskParam2 = { 0 }; /* 锁任务调度,防止新创建的任务比本任务高而发生调度 */ LOS_TaskLock(); printf("LOS_TaskLock() Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskHi; - initParam.usTaskPrio = TSK_PRIOR_HI; - initParam.pcName = "TaskHi"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; - initParam.uwResved = 0; /* detach 属性 */ + taskParam1.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi; + taskParam1.usTaskPrio = TSK_PRIOR_HI; + taskParam1.pcName = "TaskHi"; + taskParam1.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam1.uwResved = LOS_TASK_ATTR_JOINABLE; /* detach 属性 */ /* 创建高优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskHiId, &initParam); + ret = LOS_TaskCreate(&g_taskHiId, &taskParam1); if (ret != LOS_OK) { LOS_TaskUnlock(); @@ -247,13 +253,13 @@ UINT32 Example_TskCaseEntry(VOID) printf("Example_TaskHi create Success!\n"); - initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_TaskLo; - initParam.usTaskPrio = TSK_PRIOR_LO; - initParam.pcName = "TaskLo"; - initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + taskParam2.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo; + taskParam2.usTaskPrio = TSK_PRIOR_LO; + taskParam2.pcName = "TaskLo"; + taskParam2.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; /* 创建低优先级任务,由于锁任务调度,任务创建成功后不会马上执行 */ - ret = LOS_TaskCreate(&g_taskLoId, &initParam); + ret = LOS_TaskCreate(&g_taskLoId, &taskParam2); if (ret != LOS_OK) { LOS_TaskUnlock(); printf("Example_TaskLo create Failed!\n"); @@ -266,7 +272,7 @@ UINT32 Example_TskCaseEntry(VOID) LOS_TaskUnlock(); ret = LOS_TaskJoin(g_taskHiId, NULL); if (ret != LOS_OK) { - printf("Join Example_TaskHi Failed!\n"); + printf("Join Example_TaskHi Failed!, 0x%x\n", ret); } else { printf("Join Example_TaskHi Success!\n"); } @@ -279,8 +285,8 @@ UINT32 Example_TskCaseEntry(VOID) 编译运行得到的结果为: - -``` + +``` LOS_TaskLock() Success! Example_TaskHi create Success! Example_TaskLo create Success! diff --git a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md similarity index 60% rename from zh-cn/device-dev/kernel/kernel-basic-mini-time.md rename to zh-cn/device-dev/kernel/kernel-mini-basic-time.md index 36c468a90bca1d1a37daaaf698647b7454f5d29c..6e96095c08f3e74684d226fc6e7c23fe655cf997 100644 --- a/zh-cn/device-dev/kernel/kernel-basic-mini-time.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-time.md @@ -29,8 +29,8 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_MS2Tick | 毫秒转换成Tick | -| LOS_Tick2MS | Tick转化为毫秒 | +| LOS_MS2Tick | 毫秒转换成Tick。 | +| LOS_Tick2MS | Tick转化为毫秒。 | | OsCpuTick2MS | Cycle数目转化为毫秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | | OsCpuTick2US | Cycle数目转化为微秒,使用2个UINT32类型的数值分别表示结果数值的高、低32位。 | @@ -38,10 +38,23 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 | 接口名 | 描述 | | -------- | -------- | -| LOS_SysClockGet | 获取系统时钟 | -| LOS_TickCountGet | 获取自系统启动以来的Tick数 | -| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数 | +| LOS_SysClockGet | 获取系统时钟。 | +| LOS_TickCountGet | 获取自系统启动以来的Tick数。 | +| LOS_CyclePerTickGet | 获取每个Tick多少Cycle数。 | +| LOS_CurrNanosec | 获取当前的时间,单位纳秒。 | + **表3** 时间注册 + +| 接口名 | 描述 | +| --------------------- | ---------------------------------------------- | +| LOS_TickTimerRegister | 重新注册系统时钟的定时器和对应的中断处理函数。 | + + **表4** 延时 + +| 接口名 | 描述 | +| ---------- | ------------------------ | +| LOS_MDelay | 延时函数,延时单位毫秒。 | +| LOS_UDelay | 延时函数,延时单位微秒。 | ## 开发流程 @@ -56,7 +69,7 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 > > - 系统的Tick数在关中断的情况下不进行计数,故系统Tick数不能作为准确时间使用。 > -> - 配置选项维护在开发板工程的文件target_config.h。 +> - 上文描述的配置选项维护在开发板工程 target_config.h 中,部分配置项未定义的缺省值定义在内核 los_config.h中。 ## 编程实例 @@ -81,17 +94,22 @@ OpenHarmony LiteOS-M内核的时间管理提供下面几种功能,接口详细 时间转换: +本演示代码在 ./kernel/liteos_m/testsuites/src/osTest.c 中编译验证,在TestTaskEntry中调用验证入口函数ExampleTransformTime和ExampleGetTime。 + ``` -VOID Example_TransformTime(VOID) +VOID ExampleTransformTime(VOID) { UINT32 ms; UINT32 tick; - tick = LOS_MS2Tick(10000); // 10000ms转换为tick - dprintf("tick = %d \n", tick); - ms = LOS_Tick2MS(100); // 100tick转换为ms - dprintf("ms = %d \n", ms); + /* 10000ms转换为tick */ + tick = LOS_MS2Tick(10000); + printf("tick = %d \n", tick); + + /* 100tick转换为ms */ + ms = LOS_Tick2MS(100); + printf("ms = %d \n", ms); } ``` @@ -99,26 +117,21 @@ VOID Example_TransformTime(VOID) ``` -VOID Example_GetTime(VOID) +VOID ExampleGetTime(VOID) { UINT32 cyclePerTick; - UINT64 tickCount; + UINT64 tickCountBefore; + UINT64 tickCountAfter; cyclePerTick = LOS_CyclePerTickGet(); - if(0 != cyclePerTick) { - dprintf("LOS_CyclePerTickGet = %d \n", cyclePerTick); - } - - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet = %d \n", (UINT32)tickCount); + if (0 != cyclePerTick) { + printf("LOS_CyclePerTickGet = %d \n", cyclePerTick); } + tickCountBefore = LOS_TickCountGet(); LOS_TaskDelay(200); - tickCount = LOS_TickCountGet(); - if(0 != tickCount) { - dprintf("LOS_TickCountGet after delay = %d \n", (UINT32)tickCount); - } + tickCountAfter = LOS_TickCountGet(); + printf("LOS_TickCountGet after delay rising = %d \n", (UINT32)(tickCountAfter - tickCountBefore)); } ``` @@ -138,8 +151,7 @@ ms = 1000 时间统计和时间延迟: -``` -LOS_CyclePerTickGet = 495000 -LOS_TickCountGet = 1 -LOS_TickCountGet after delay = 201 +``` +LOS_CyclePerTickGet = 250000 (根据实际运行环境,数据会有差异) +LOS_TickCountGet after delay rising = 200 ``` diff --git a/zh-cn/device-dev/kernel/kernel-standard-newip.md b/zh-cn/device-dev/kernel/kernel-standard-newip.md index c507257656f86fa1c9dcd862e22ba78ae9433940..5c1d9dade804eba1d0b9066132cd2d50298131e0 100644 --- a/zh-cn/device-dev/kernel/kernel-standard-newip.md +++ b/zh-cn/device-dev/kernel/kernel-standard-newip.md @@ -254,7 +254,7 @@ struct sockaddr_nin { ![zh-cn_image-20221009112548444](figures/zh-cn_image-20221009112548444.png) -上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 +上图中NewIP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置NewIP地址和路由。 | 文件名 | 功能 | | ------------------ | ------------------------------------------------------ | @@ -284,7 +284,7 @@ struct sockaddr_nin { ## NewIP收发包代码示例 -NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony-sig/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 +NewIP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,NewIP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony/communication_sfc_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。 | 文件名 | 功能 | | --------------------- | ----------------------------- | @@ -383,7 +383,7 @@ allowxperm thread_xxx thread_xxx:socket ioctl { 0x8933 0x8916 0x890B }; ## WireShark报文解析模板 -Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony-sig/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 +Wireshark默认报文解析规则无法解析NewIP报文,在WireShark配置中添加NewIP报文解析模板可以实现NewIP报文解析,[NewIP报文解析模板](https://gitee.com/openharmony/communication_sfc_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。 报文解析模板配置文件的方法: 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-stm32f407-on-minisystem-eth.md b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md index 29de44f87158ba6f2d54bbe62de2a98413161f38..2c737a460b35f81ad954e496a21467a42c8f53da 100644 --- a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md +++ b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md @@ -715,7 +715,7 @@ board_ld_flags :链接选项,与Makefile中的LDFLAGS变量对应。 ### 内核基础功能适配 -内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-basic-mini-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 +内核基础功能适配项包括:**[中断管理](../kernel/kernel-mini-basic-interrupt.md)**、**[任务管理](../kernel/kernel-mini-basic-task.md)**、**[内存管理](../kernel/kernel-mini-basic-memory.md)**、**[内核通信机制](../kernel/kernel-mini-basic-ipc-event.md)**、**[时间管理](../kernel/kernel-mini-basic-time.md)**、**[软件定时器](../kernel/kernel-mini-basic-soft.md)**,可以参考对应链接中的编程实例进行内核基础功能验证。在验证的过程中发现问题,针对相应问题进行具体的适配。 从上一节中打印信息输出时间间隔可以看出,`LOS_TaskDelay`函数的延时时间不准确,我们可以在`target_config.h`中定义如下宏进行内核时钟适配: 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/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 3aca6a69afabb10c047aed0b228025b0f4c283b4..901db72406063e38d4675440075e1b915d050bc3 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -82,6 +82,8 @@ - [系统参数](subsys-boot-init-sysparam.md) - [沙盒管理](subsys-boot-init-sandbox.md) - [插件](subsys-boot-init-plugin.md) + - [组件化启动](subsys-boot-init-sub-unit.md) + - [init运行日志规范化](subsys-boot-init-log.md) - [appspawn应用孵化组件](subsys-boot-appspawn.md) - [bootstrap服务启动组件](subsys-boot-bootstrap.md) - [常见问题](subsys-boot-faqs.md) diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-log.md b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md new file mode 100644 index 0000000000000000000000000000000000000000..f7e67b7d31bee1e67f7957ca9182d6748528e7dc --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md @@ -0,0 +1,74 @@ +# init运行时日志规范化 +## 概述 +### 功能简介 +日志的基本功能就是记录init启动中的关键节点,以及定位故障问题。 +- 基于日志可以定位故障问题,可以查看各子系统启动时长,命令执行时长等。 +- 可以查看不同模块的日志tag,如param、uevent、module等。 +- 输出关键阶段日志,如第一阶段启动日志、required partition设备节点、uevent创建日志、服务启动日志等。 +- 日志等级可控,根据需要输出不同级别日志,目前日志级别分为INIT_DEBUG, +INIT_INFO,INIT_WARN,INIT_ERROR,INIT_FATAL。 + +### 基本概念 + +init日志根据OpenHarmony版本不同实现方式不同。 +- 对于OpenHarmony标准版本,init日志采用内核的dmesg log实现。 +- 对于OpenHarmony liteos L1版本init日志采用hilog接口实现。 +- 对于OpenHarmony liteos L0版本init日志采用printf接口实现。 + +### 约束与限制 +无 + +## 开发指导 +### 场景介绍 +init log主要应用在init的启动过程中,启动相关模块(param、ueventd、module等)中,以及对外提供的begetutils接口中。 + +### 接口说明 + +**表1** log接口说明 + | 接口 | 接口格式和示例 | 说明 | + | -------- | -------- | -------- | + | INIT_LOGV | INIT_LOGV("Add %s to job %s", service->name, jobName); | 输出debug log。 | + | INIT_LOGI | INIT_LOGI("Start init first stage."); | 输出info log。 | + | INIT_LOGW | INIT_LOGW("initialize signal handler failed"); | 输出warning log。 | + | INIT_LOGE | INIT_LOGE("Failed to format other opt"); | 输出err log。 | + | INIT_LOGF | INIT_LOGF("Failed to init system"); | 输出fatal log。 | + | INIT_ERROR_CHECK | INIT_ERROR_CHECK(ctx != NULL, return NULL, "Failed to get cmd args "); | 判断 ctx != NULL 不成立的情况下输出log,同时执行 return NULL。 | + | INIT_INFO_CHECK | INIT_INFO_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Failed to malloc for service %s", service->name); | 判断 sockopt != NULL 不成立的情况下输出log,同时执行 return SERVICE_FAILURE。 | + | INIT_WARNING_CHECK | INIT_WARNING_CHECK(argsCount <= SPACES_CNT_IN_CMD_MAX, argsCount = SPACES_CNT_IN_CMD_MAX, "Too much arguments for command, max number is %d", SPACES_CNT_IN_CMD_MAX); | 判断 argsCount <= SPACES_CNT_IN_CMD_MAX 不成立的情况下输出log,同时执行 argsCount = SPACES_CNT_IN_CMD_MAX。 | + | INIT_CHECK | INIT_CHECK(arg != NULL, return NULL); | 判断arg != NULL 不成立的情况下执行 return NULL。 | + | INIT_CHECK_RETURN_VALUE | INIT_CHECK_RETURN_VALUE(errno == 0, -1); | 判断errno == 0 不成立的情况下执行 return -1。 | + | INIT_CHECK_ONLY_RETURN | INIT_CHECK_ONLY_RETURN(cmd != NULL); | 判断cmd != NULL 不成立的情况下执行 return。 | + | INIT_CHECK_ONLY_ELOG | INIT_CHECK_ONLY_ELOG(execv(argv[0], argv) == 0, "execv %s failed! err %d.", argv[0], errno); | 判断execv(argv[0], argv) == 0 不成立的情况下只打印log "execv %s failed! err %d."。 | + +### 开发实例 + + 1. 调用接口打印日志 + + 例如在 //base/startup/init/services/init/standard/init.c中调用接口INIT_LOGI("Start init first stage.")打印日志。 + ```c + void SystemPrepare(void) + { + MountBasicFs(); + CreateDeviceNode(); + LogInit(); + // Make sure init log always output to /dev/kmsg. + EnableDevKmsg(); + INIT_LOGI("Start init first stage."); + // Only ohos normal system support + // two stages of init. + // If we are in updater mode, only one stage of init. + if (InUpdaterMode() == 0) { + StartInitSecondStage(); + } + } + ``` + 通过dmesg可以查看打印的log,"Start init first stage."。 + + 2. 通过命令设置日志等级 + + 通过命令begetctl setloglevel level,其中level对应log的等级0~4,即INIT_DEBUG,INIT_INFO,INIT_WARN,INIT_ERROR,INIT_FATAL。 + + 设置完成之后init的g_logLevel等级立即生效,上述log接口中log等级大于等于g_logLevel才会打印日志。例如:begetctl setloglevel 3,即设置log等级为INIT_ERROR,则上述的log接口中只有INIT_LOGE、INIT_LOGF才会打印log。 + + 系统重启之后在init.cfg中"load_persist_params "命令之后生效设置的log等级。 + diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md b/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md index 69e3b2dc032c90905ea40f8475c3bb6acf56f545..0612e4eb70e19f00940c20f890f60b87f9c3b10b 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @@ -59,6 +59,8 @@ bootchart和bootevent只支持标准系统, begetctl 支持小型系统和标 | modulectl uninstall moduleName | 卸载动态插件,例如:
modulectl uninstall bootchart | 无 | | modulectl install moduleName | 安装动态插件,例如:
modulectl install bootchart | 无 | | modulectl list | 动态插件列表,例如:
begetctl modulectl list | 无 | +| setloglevel level | 设置log等级为info,例如:
begetctl setloglevel 1 | log等级设置范围0~4 | +| getloglevel | 获取当前init的log等级,例如:
begetctl getloglevel | 无 | | bootevent disable | 关闭bootevent插件功能,例如:
bootevent disable | 无 | | bootevent enable | 开启bootevent插件功能,例如:
begetctl 关闭bootevent插件功能 | 无 | | dump_service parameter_service trigger | 命令行展示所有trigger信息,例如:
begetctl dump_service parameter_service trigger | 无 | @@ -67,16 +69,6 @@ bootchart和bootevent只支持标准系统, begetctl 支持小型系统和标 | dump api | 命令行展示init接口信息,例如:
begetctl dump api | 无 | -### 接口说明 - - **表1** 接口介绍 -| 函数 | 函数解释 | -| ---------- | ---------- | -| void PluginExecCmdByName(const char *name, const char *cmdContent) | 通过名称启动插件。 | -| void PluginExecCmdByCmdIndex(int index, const char *cmdContent) | 通过标志启动插件。 | -| int PluginExecCmd(const char *name, int argc, const char **argv) | 命令启动插件。 | -| int AddCmdExecutor(const char *cmdName, CmdExecutor execCmd) | 添加安装插件命令。 | - ### 开发步骤 新增一个插件, 以bootchart为例: 1. 安装so文件, 定义单独文件,实现下面函数。 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md b/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md index 0fd7c44f7e6fbe995fe8d26dd0cf13da5e1942a2..bfb9ad418ce7b7268ad2aabee9a8fc790f195e50 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @@ -23,6 +23,7 @@ | src-path | 需要mount的目录/文件路径 | | sandbox-path | 沙盒里面需要挂载至的目录/文件 | | sandbox-flags | mount的挂载标志位, 缺省"bind rec"标志位 | + | ignore | 是否忽略mount失败,设置为1 则忽略失败,继续往下执行 | | target-name | 需要link的目录 | | link-name | 沙盒内link后的目录 | @@ -43,13 +44,13 @@ bool InitSandboxWithName(const char *name); // 解析JSON至结构体 typedef struct { - mountlist_t *mounts; // 待 mount 的目录 - mountlist_t *fileMounts; // 待 mount 的文件 - linklist_t *links; // 待 link 的目录 - char *rootPath; // 沙盒的根路径 -> /mnt/sandbox/system|vendor|xxx - char name[MAX_BUFFER_LEN]; // 沙盒名称,system沙盒、chipset沙盒等 - bool isCreated; // 沙盒创建标志 - int ns; // namespace + ListNode pathMountsHead; // sandbox mount_path list head + ListNode fileMountsHead; // sandbox mount_file list head + ListNode linksHead; // sandbox symbolic link list head + char *rootPath; // /mnt/sandbox/system|vendor|xxx + char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc. + bool isCreated; // sandbox already created or not + int ns; // namespace } sandbox_t; ``` ### 开发步骤 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md b/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md new file mode 100644 index 0000000000000000000000000000000000000000..06e7419723eae6063f99cda96bfa6101c0e241d9 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md @@ -0,0 +1,120 @@ +# 组件化启动 +## 概述 +### 功能简介 +构建四个基础组件镜像,提供相应的组件化目录,包括: +- 系统组件:system +- 产品通用配置组件:sys_prod +- 芯片组件:chipset +- 产品硬件配置组件:chip_prod; + +确保系统参数以及启动脚本都可以按照组件的优先级进行扫描初始化; +完成系统组件和芯片组件的独立编译构建。 +### 基本概念 +- 基础组件 + + system:系统组件文件系统挂载点,与芯片及硬件无关的平台业务; + sys_prod:对系统组件的能力扩展以及能力定制,承载产品级差异能力,存放产品相关的配置文件; + chipset:芯片组件文件系统挂载点,为系统组件提供统一的硬件抽象服务,相同的芯片平台可统一一份芯片组件; + chip_prod:单板外设特有硬件能力以及产品级硬件差异配置, 存放芯片相关的配置文件。 + +- 组件化编译构建 + + 通过"target_cpu" 指定系统组件的指令集;通过"inherit" 继承base、headless或者rich等通用组件集合;最后通过"subsystems" 定义该形态更多的部件。 + +- 系统参数以及启动脚本按照组件的优先级进行扫描初始化 + + 系统参数以及启动脚本包括:服务的cfg配置文件、param文件、沙盒json配置文件以及module插件化库文件等。相关文件优先级顺序是 /system < /chipset < /sys_prod < /chip_prod,即优先级高的配置文件将取代、更新低优先级配置。 + + +### 约束与限制 +对于标准版本和小型系统都支持组件化编译构建,以及系统参数以及启动脚本按照组件的优先级进行扫描初始化。 + +## 开发指导 +### 场景介绍 +组件化启动主要是满足厂家、硬件平台通过模块化的组合快速实现产品开发。以下以rk3568产品为例介绍组件化启动。 + +### rk3568产品的组件化构建编译 +//vendor/hihope/rk3568/config.json 配置文件实现构建此产品需要的组件,如下所示: + + { + "product_name": "rk3568", + "device_company": "rockchip", + ... + "target_cpu": "arm", + ... + "inherit": [ "productdefine/common/inherit/rich.json", "productdefine/common/inherit/chipset_common.json" ], + "subsystems": [ + { + "subsystem": "security", + "components": [ + { + "component": "selinux", + "features": [] + } + ] + } + ... + } + +从中可以看出产品名称、芯片厂家、支持的指令集等;inherit指出依赖的通用组件;subsystems指出通用组件以外的部件。 +//productdefine/common/inherit/rich.json 如下所示配置系统组件完整的部件;系统组件还可以包括base.json(所有产品都要包含的最小部件集合列表)、headless.json(没有ui界面的产品支持应用安装管理的最小部件集合)。 + + { + "version": "3.0", + "subsystems": [ + { + "subsystem": "arkui", + "components": [ + { + "component": "ace_engine", + "features": [] + }, + { + "component": "napi", + "features": [] + } + ] + }, + { + "subsystem": "account", + "components": [ + { + "component": "os_account", + "features": [] + } + ] + }, + ... + } + +### 系统参数根据优先级扫描初始化 +对于服务的cfg配置文件优先级是/system/etc < /system/etc/init < /chipset/etc,即优先级高的配置文件将取代、更新低优先级配置。例如/system/etc/init/camera_service.cfg, + + { + "services" : [{ + "name" : "camera_service", + "path" : ["/system/bin/sa_main", "/system/profile/camera_service.xml"], + "uid" : "cameraserver", + "gid" : ["system", "shell"], + "secon" : "u:r:camera_service:s0", + "permission" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "permission_acls" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"] + }] + } + +同时存在/chipset/etc/camera_B_service.cfg + + { + "services" : [{ + "name" : "camera_service", + "path" : ["/system/bin/sa_main", "/system/profile/camera_B_service.xml"], + "uid" : "cameraserver", + "gid" : ["system", "shell"], + "secon" : "u:r:camera_service:s0", + "permission" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "permission_acls" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "disabled" : 1 + }] + } + +那么根据优先级的要求,camera_service服务"path"属性将会被优先级高的["/system/bin/sa_main", "/system/profile/camera_B_service.xml"]取代,同时增加"disabled"属性。 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/device-dev/website.md b/zh-cn/device-dev/website.md index f26f2863bbd04c491f1e4ab3b90d6057e057cf9f..23c3473248d2c2e9109b122e07dac851043bb449 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -166,8 +166,9 @@ - [互斥锁](kernel/kernel-mini-basic-ipc-mutex.md) - [消息队列](kernel/kernel-mini-basic-ipc-queue.md) - [信号量](kernel/kernel-mini-basic-ipc-sem.md) - - [时间管理](kernel/kernel-basic-mini-time.md) + - [时间管理](kernel/kernel-mini-basic-time.md) - [软件定时器](kernel/kernel-mini-basic-soft.md) + - [双向链表](kernel/kernel-mini-basic-list.md) - 扩展组件 - [C++支持](kernel/kernel-mini-extend-support.md) - [CPU占用率](kernel/kernel-mini-extend-cpup.md) @@ -180,7 +181,6 @@ - [LMS调测](kernel/kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel/kernel-mini-appx-code.md) - - [双向链表](kernel/kernel-mini-appx-data-list.md) - [标准库支持](kernel/kernel-mini-appx-lib.md) - 小型系统内核(LiteOS-A) - [小型系统内核概述](kernel/kernel-small-overview.md) 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/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" index 2a5c008647203981e2da766e24c29bb14173d476..123e8b3acb357954dac6cb1c00e7db9ad3a90df6 100644 --- "a/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\224\250\346\210\267IAM\345\255\220\347\263\273\347\273\237.md" @@ -1,20 +1,12 @@ # 用户IAM子系统 -- [简介](#简介) -- [目录](#目录) -- [约束](#约束) -- [说明](#说明) - - [使用说明](#使用说明) -- [相关仓](#相关仓) - - ## 简介 用户身份和访问管理子系统,下称用户IAM(Identity and Access Management),旨在为OpenHarmony提供统一用户身份凭据信息管理和用户身份认证框架能力,支持多用户分别设置认证凭据信息,并根据用户设置的认证凭据信息提供用户身份认证功能,支撑锁屏等安全场景。同时,用户IAM子系统也提供API,支持三方开发者调用系统提供的身份认证能力来实现业务对用户的访问控制要求。 **图1** 子系统架构图 -用户IAM子系统逻辑架构 +![](figures/用户IAM子系统逻辑架构.png) 用户IAM子系统分为统一用户认证框架和认证执行器两个部分,其中**统一用户认证框架**部分包含: 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/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index 58f46c6929ab2f5cbcdeb4a0f3340e4cce3de5a3..16c8318d068221441622c4b6ac881424c84c6bde 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -170,7 +170,9 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持设备级的跨设备剪贴板开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。
主要涉及如下需求:
I5IZZ7 【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius
I5JQ1R 【ace_engine_standard部件】支持图片复制粘贴
I5JQ3F 【ace_engine_standard部件】输入框能力增强
I5JQ3J 【ace_engine_standard部件】stack组件新增事件拓传机制
I5JQ54 【ace_engine_standard部件】指定控件获取焦点
I5MX7J 【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果
I5MWS0 【ace_engine_standard部件】panel组件弹出高度通知给开发者
I5IZVY 【ace_engine_standard部件】键鼠接入时支持组件刷新
I5JQ5Y 【ace_engine_standard部件】走焦能力增强
I5IY7K 【新增需求】【ace_engine_standard部件】主题能力支持
I5MWTB 【ace_engine_standard部件】媒体查询支持vp查询
I5IZU9 【ace_engine_standard部件】ui_service常驻内存优化
I5JQ26 【ace_engine_standard部件】Vsync请求机制流程优化
I5JQ2O 【ace_engine部件】公共资源预加载
I5JQ2D 【ace_engine_standard部件】Move事件重采样优化
I5IZXS 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZYG 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZX0 【toolchain部件】编译支持解析$r新增bundleName和moduleName参数
I5J09I 【toolchain部件】\@Builder 支持export导出 | NA | +API变更请参考: +[*API差异报告*](api-change/v3.2-beta3/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.1-Release/changelog-v3.1-release.md b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md index 4c7289ed1c70c6171775bf34f9701689e94e5792..39a5affa00e6649dc1ebf3d54d2311bb33e7813f 100644 --- a/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md +++ b/zh-cn/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md @@ -18,4 +18,39 @@ **关键的接口/组件变更** -无 \ No newline at end of file +无 + +### 状态变量多种数据类型声明使用限制。 + +状态变量比如@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-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..a655be51c328a29689b273121e163a455888959a 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,4 @@ OpenHarmony应用沙箱组件 ![](figures/compile-change2-1.png) -![](figures/compile-change2-2.png) \ No newline at end of file +![](figures/compile-change2-2.png) 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中颜色值,增加合法性校验 diff --git a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md index 7cc610cb724ef4aaa126750f3f4781028cc5de96..f905b19e94e376e0abaf0e50718ddfb5db31320a 100644 --- a/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md +++ b/zh-cn/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md @@ -36,4 +36,6 @@ OpenHarmony 3.2 Beta3版本相较于OpenHarmony 3.2 Beta2版本,电源服务 | system.brightness | GetBrightnessOptions | complete?: () => void; | 废弃 | | system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | 废弃 | | system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | 废弃 | -| system.brightness | BrightnessResponse | value: number; | 废弃 | \ No newline at end of file +| system.brightness | BrightnessResponse | value: number; | 废弃 | +| ohos.batteryInfo | batteryInfo | ohos.batteryinfo -> ohos.batteryInfo | 模块名修改 | +