From 3dc4f5351dcc5abf68b301a04bd87d499b7f5c33 Mon Sep 17 00:00:00 2001 From: zengyawen Date: Thu, 14 Apr 2022 16:00:44 +0800 Subject: [PATCH] update docs Signed-off-by: zengyawen --- .../reference/apis/Readme-EN.md | 321 +- .../figures/en-us_image_0000001200913929.png | Bin 0 -> 9907 bytes .../reference/apis/js-apis-Bundle.md | 1047 ++-- .../reference/apis/js-apis-Context.md | 8 +- .../reference/apis/js-apis-ability-context.md | 495 -- .../apis/js-apis-ability-errorCode.md | 25 + .../apis/js-apis-ability-wantConstant.md | 88 + .../apis/js-apis-abilityAccessCtrl.md | 4 +- .../apis/js-apis-abilityDelegatorRegistry.md | 76 + .../apis/js-apis-abilityrunninginfo.md | 4 +- .../apis/js-apis-abilitystagecontext.md | 33 - .../reference/apis/js-apis-appAccount.md | 705 ++- .../js-apis-application-MissionSnapshot.md | 6 +- .../apis/js-apis-application-Want.md | 30 + .../apis/js-apis-application-ability.md | 587 --- .../js-apis-application-abilityConstant.md | 56 - .../js-apis-application-abilityDelegator.md | 239 + ...s-apis-application-abilityDelegatorArgs.md | 24 + .../apis/js-apis-application-abilitystage.md | 99 - .../apis/js-apis-application-context.md | 80 - .../js-apis-application-shellCmdResult.md | 22 + .../reference/apis/js-apis-appmanager.md | 73 +- .../reference/apis/js-apis-arraylist.md | 11 + .../apis/js-apis-backgroundTaskManager.md | 112 +- .../reference/apis/js-apis-bluetooth.md | 36 +- .../reference/apis/js-apis-commonEvent.md | 430 +- .../reference/apis/js-apis-configuration.md | 11 +- .../apis/js-apis-configurationconstant.md | 52 +- .../reference/apis/js-apis-connectedTag.md | 223 + .../reference/apis/js-apis-convertxml.md | 36 +- .../reference/apis/js-apis-data-ability.md | 2490 +++------- .../apis/js-apis-data-distributedobject.md | 92 +- .../reference/apis/js-apis-data-rdb.md | 1388 +++--- .../reference/apis/js-apis-data-resultset.md | 1082 ++-- .../reference/apis/js-apis-data-storage.md | 67 +- .../apis/js-apis-dataAbilityHelper.md | 3 + .../reference/apis/js-apis-deque.md | 7 +- .../reference/apis/js-apis-device-manager.md | 611 +-- .../apis/js-apis-deviceUsageStatistics.md | 38 +- .../reference/apis/js-apis-display.md | 4 +- .../apis/js-apis-distributed-account.md | 369 +- .../apis/js-apis-distributed-data.md | 4389 ++++++++--------- .../reference/apis/js-apis-eventhub.md | 140 - .../apis/js-apis-extension-context.md | 6 +- .../apis/js-apis-extensionrunninginfo.md | 38 +- .../reference/apis/js-apis-featureAbility.md | 422 +- .../reference/apis/js-apis-fileio.md | 1573 ++++-- .../reference/apis/js-apis-filemanager.md | 2 +- .../reference/apis/js-apis-formInfo.md | 116 + .../reference/apis/js-apis-formbindingdata.md | 20 +- .../reference/apis/js-apis-formerror.md | 49 + .../reference/apis/js-apis-formextension.md | 219 - .../reference/apis/js-apis-formhost.md | 1010 ++++ .../reference/apis/js-apis-formprovider.md | 12 + .../reference/apis/js-apis-geolocation.md | 882 ++-- .../reference/apis/js-apis-hashmap.md | 10 +- .../reference/apis/js-apis-hashset.md | 2 +- .../reference/apis/js-apis-hiappevent.md | 101 +- .../reference/apis/js-apis-hichecker.md | 50 +- .../reference/apis/js-apis-hidebug.md | 78 +- .../reference/apis/js-apis-hilog.md | 85 +- .../reference/apis/js-apis-hitracechain.md | 10 +- .../reference/apis/js-apis-hitracemeter.md | 14 +- .../reference/apis/js-apis-huks.md | 1191 +++++ .../reference/apis/js-apis-i18n.md | 986 ++-- .../reference/apis/js-apis-image.md | 503 +- .../reference/apis/js-apis-inputdevice.md | 201 +- .../apis/js-apis-inputeventclient.md | 57 + .../reference/apis/js-apis-inputmethod.md | 208 + .../apis/js-apis-inputmethodengine.md | 756 +++ .../reference/apis/js-apis-inputmonitor.md | 118 +- .../reference/apis/js-apis-intl.md | 482 +- .../reference/apis/js-apis-lightweightmap.md | 4 +- .../reference/apis/js-apis-lightweightset.md | 4 +- .../reference/apis/js-apis-linkedlist.md | 13 +- .../reference/apis/js-apis-list.md | 20 +- .../reference/apis/js-apis-logs.md | 205 +- .../reference/apis/js-apis-media.md | 205 +- .../reference/apis/js-apis-medialibrary.md | 448 +- .../reference/apis/js-apis-mediaquery.md | 145 + .../reference/apis/js-apis-missionManager.md | 148 +- .../reference/apis/js-apis-net-connection.md | 83 +- .../reference/apis/js-apis-notification.md | 3423 +++++++------ .../reference/apis/js-apis-observer.md | 6 +- .../reference/apis/js-apis-osAccount.md | 31 +- .../reference/apis/js-apis-particleAbility.md | 48 +- .../apis/js-apis-permissionrequestresult.md | 17 - .../reference/apis/js-apis-plainarray.md | 16 +- .../reference/apis/js-apis-power.md | 14 +- .../apis/js-apis-processrunninginfo.md | 2 +- .../reference/apis/js-apis-prompt.md | 272 + .../reference/apis/js-apis-queue.md | 1 + .../reference/apis/js-apis-radio.md | 4 +- .../reference/apis/js-apis-reminderAgent.md | 147 +- .../apis/js-apis-resource-manager.md | 286 +- .../reference/apis/js-apis-router.md | 434 ++ .../reference/apis/js-apis-runninglock.md | 36 +- .../reference/apis/js-apis-sensor.md | 1454 +++--- .../apis/js-apis-service-extension-ability.md | 161 - .../apis/js-apis-service-extension-context.md | 2 +- .../reference/apis/js-apis-sim.md | 4 +- .../reference/apis/js-apis-stack.md | 2 + .../apis/js-apis-storage-statistics.md | 3 +- .../reference/apis/js-apis-system-app.md | 214 + .../reference/apis/js-apis-system-battery.md | 55 + .../apis/js-apis-system-brightness.md | 202 + .../reference/apis/js-apis-system-cipher.md | 165 + .../apis/js-apis-system-configuration.md | 45 + .../reference/apis/js-apis-system-device.md | 75 + .../reference/apis/js-apis-system-fetch.md | 105 + .../reference/apis/js-apis-system-file.md | 601 +++ .../reference/apis/js-apis-system-location.md | 211 + .../apis/js-apis-system-mediaquery.md | 125 + .../reference/apis/js-apis-system-network.md | 134 + .../reference/apis/js-apis-system-package.md | 60 + .../reference/apis/js-apis-system-prompt.md | 188 + .../reference/apis/js-apis-system-request.md | 189 + .../reference/apis/js-apis-system-router.md | 398 ++ .../reference/apis/js-apis-system-storage.md | 162 + .../reference/apis/js-apis-system-time.md | 32 +- .../reference/apis/js-apis-testRunner.md | 51 + .../reference/apis/js-apis-treemap.md | 24 +- .../reference/apis/js-apis-treeset.md | 7 +- .../reference/apis/js-apis-uitest.md | 1058 ++++ .../apis/js-apis-uripermissionmanager.md | 78 - .../reference/apis/js-apis-usb.md | 121 +- .../apis/js-apis-useriam-userauth.md | 1386 +++--- .../reference/apis/js-apis-util.md | 78 +- .../reference/apis/js-apis-vector.md | 19 +- .../reference/apis/js-apis-vibrator.md | 100 +- .../reference/apis/js-apis-wantAgent.md | 22 +- .../reference/apis/js-apis-webSocket.md | 2 +- .../reference/apis/js-apis-wifi.md | 38 +- .../reference/apis/js-apis-wifiext.md | 16 +- .../reference/apis/js-apis-window.md | 50 +- .../reference/apis/js-apis-xml.md | 2 +- .../reference/apis/js-apis-zlib.md | 13 +- 137 files changed, 22354 insertions(+), 16124 deletions(-) create mode 100644 en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png delete mode 100644 en/application-dev/reference/apis/js-apis-ability-context.md create mode 100644 en/application-dev/reference/apis/js-apis-ability-errorCode.md create mode 100644 en/application-dev/reference/apis/js-apis-ability-wantConstant.md create mode 100644 en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md delete mode 100644 en/application-dev/reference/apis/js-apis-abilitystagecontext.md create mode 100644 en/application-dev/reference/apis/js-apis-application-Want.md delete mode 100644 en/application-dev/reference/apis/js-apis-application-ability.md delete mode 100644 en/application-dev/reference/apis/js-apis-application-abilityConstant.md create mode 100644 en/application-dev/reference/apis/js-apis-application-abilityDelegator.md create mode 100644 en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md delete mode 100644 en/application-dev/reference/apis/js-apis-application-abilitystage.md delete mode 100644 en/application-dev/reference/apis/js-apis-application-context.md create mode 100644 en/application-dev/reference/apis/js-apis-application-shellCmdResult.md create mode 100644 en/application-dev/reference/apis/js-apis-connectedTag.md delete mode 100644 en/application-dev/reference/apis/js-apis-eventhub.md create mode 100644 en/application-dev/reference/apis/js-apis-formInfo.md create mode 100644 en/application-dev/reference/apis/js-apis-formerror.md delete mode 100644 en/application-dev/reference/apis/js-apis-formextension.md create mode 100644 en/application-dev/reference/apis/js-apis-formhost.md create mode 100644 en/application-dev/reference/apis/js-apis-huks.md create mode 100644 en/application-dev/reference/apis/js-apis-inputeventclient.md create mode 100644 en/application-dev/reference/apis/js-apis-inputmethod.md create mode 100644 en/application-dev/reference/apis/js-apis-inputmethodengine.md create mode 100644 en/application-dev/reference/apis/js-apis-mediaquery.md delete mode 100644 en/application-dev/reference/apis/js-apis-permissionrequestresult.md create mode 100644 en/application-dev/reference/apis/js-apis-prompt.md create mode 100644 en/application-dev/reference/apis/js-apis-router.md delete mode 100644 en/application-dev/reference/apis/js-apis-service-extension-ability.md create mode 100644 en/application-dev/reference/apis/js-apis-system-app.md create mode 100644 en/application-dev/reference/apis/js-apis-system-battery.md create mode 100644 en/application-dev/reference/apis/js-apis-system-brightness.md create mode 100644 en/application-dev/reference/apis/js-apis-system-cipher.md create mode 100644 en/application-dev/reference/apis/js-apis-system-configuration.md create mode 100644 en/application-dev/reference/apis/js-apis-system-device.md create mode 100644 en/application-dev/reference/apis/js-apis-system-fetch.md create mode 100644 en/application-dev/reference/apis/js-apis-system-file.md create mode 100644 en/application-dev/reference/apis/js-apis-system-location.md create mode 100644 en/application-dev/reference/apis/js-apis-system-mediaquery.md create mode 100644 en/application-dev/reference/apis/js-apis-system-network.md create mode 100644 en/application-dev/reference/apis/js-apis-system-package.md create mode 100644 en/application-dev/reference/apis/js-apis-system-prompt.md create mode 100644 en/application-dev/reference/apis/js-apis-system-request.md create mode 100644 en/application-dev/reference/apis/js-apis-system-router.md create mode 100644 en/application-dev/reference/apis/js-apis-system-storage.md create mode 100644 en/application-dev/reference/apis/js-apis-testRunner.md create mode 100644 en/application-dev/reference/apis/js-apis-uitest.md delete mode 100644 en/application-dev/reference/apis/js-apis-uripermissionmanager.md diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 0887ba201b..092d3f2373 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,122 +1,223 @@ # APIs - Ability Framework - - [FeatureAbility Module](js-apis-featureAbility.md) - - [ParticleAbility Module](js-apis-particleAbility.md) - - [DataAbilityHelper Module](js-apis-dataAbilityHelper.md) - - [DataUriUtils Module](js-apis-DataUriUtils.md) - - [Bundle Module](js-apis-Bundle.md) - - [Context Module](js-apis-Context.md) -- Event Notification - - [CommonEvent Module](js-apis-commonEvent.md) - - [Notification Module](js-apis-notification.md) - - [Reminder Agent](js-apis-reminderAgent.md) -- Resource Management - - [Resource Manager](js-apis-resource-manager.md) - - [Internationalization \(intl\) ](js-apis-intl.md) - - [Internationalization \(i18n\) ](js-apis-i18n.md) + + - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) + - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) + - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) + - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) + - [@ohos.application.appManager](js-apis-appmanager.md) + - [@ohos.application.Configuration](js-apis-configuration.md) + - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) + - [@ohos.ability.featureAbility](js-apis-featureAbility.md) + - [@ohos.application.formBindingData](js-apis-formbindingdata.md) + - [@ohos.application.formError](js-apis-formerror.md) + - [@ohos.application.formHost](js-apis-formhost.md) + - [@ohos.application.formInfo](js-apis-formInfo.md) + - [@ohos.application.missionManager](js-apis-missionManager.md) + - [@ohos.application.formProvider](js-apis-formprovider.md) + - [@ohos.ability.particleAbility](js-apis-particleAbility.md) + - [@ohos.application.Want](js-apis-application-Want.md) + - [@ohos.wantAgent](js-apis-wantAgent.md) + - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) + - app/[context](js-apis-Context.md) + - application/[abilityDelegator](js-apis-application-abilityDelegator.md) + - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) + - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) + - application/[ExtensionContext](js-apis-extension-context.md) + - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) + - application/[FormExtensionContext](js-apis-formextensioncontext.md) + - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) + - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) + - application/[ServiceExtensionContext](js-apis-service-extension-context.md) + - application/[shellCmdResult](js-apis-application-shellCmdResult.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) +- Bundle Management + + - [@ohos.bundle](js-apis-Bundle.md) + - [@ohos.bundleState ](js-apis-deviceUsageStatistics.md) + - [@ohos.zlib](js-apis-zlib.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) + +- Graphics + + - [@ohos.display ](js-apis-display.md) + - [@ohos.screenshot](js-apis-screenshot.md) + - [@ohos.window](js-apis-window.md) + - [webgl](js-apis-webgl.md) + - [webgl2](js-apis-webgl2.md) + - Media - - [Audio Management](js-apis-audio.md) - - [Media](js-apis-media.md) - - [Image Processing](js-apis-image.md) - - [Camera](js-apis-camera.md) + + - [@ohos.multimedia.audio](js-apis-audio.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 + + - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) + +- Custom Management + + - [@ohos.configPolicy](js-apis-config-policy.md) + - Security - - [User Authentication](js-apis-useriam-userauth.md) - - [Access Control](js-apis-abilityAccessCtrl.md) + + - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) + - [@ohos.security.huks ](js-apis-huks.md) + - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) + - [@system.cipher](js-apis-system-cipher.md) + - Data Management - - [Lightweight Storage](js-apis-data-storage.md) - - [Distributed Data Management](js-apis-distributed-data.md) - - [Relational Database](js-apis-data-rdb.md) - - [Result Set](js-apis-data-resultset.md) - - [DataAbilityPredicates](js-apis-data-ability.md) - - [Settings](js-apis-settings.md) + + - [@ohos.data.dataAbility ](js-apis-data-ability.md) + - [@ohos.data.distributedData](js-apis-distributed-data.md) + - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) + - [@ohos.data.rdb](js-apis-data-rdb.md) + - [@ohos.settings](js-apis-settings.md) + - data/rdb/[resultSet](js-apis-data-resultset.md) + - File Management - - [File Management](js-apis-fileio.md) - - [Statfs](js-apis-statfs.md) - - [Environment](js-apis-environment.md) - - [Public File Access and Management](js-apis-filemanager.md) - - [App Storage Statistics](js-apis-storage-statistics.md) -- Account Management - - [OS Account Management](js-apis-osAccount.md) - - [Distributed Account Management](js-apis-distributed-account.md) - - [App Account Management](js-apis-appAccount.md) + + - [@ohos.environment](js-apis-environment.md) + - [@ohos.fileio](js-apis-fileio.md) + - [@ohos.fileManager](js-apis-filemanager.md) + - [@ohos.statfs](js-apis-statfs.md) + - [@ohos.storageStatistics](js-apis-storage-statistics.md) + - Telephony Service - - [Call](js-apis-call.md) - - [SMS](js-apis-sms.md) - - [SIM Management](js-apis-sim.md) - - [Radio](js-apis-radio.md) - - [Observer](js-apis-observer.md) - - [Cellular Data](js-apis-telephony-data.md) + + - [@ohos.contact](js-apis-contact.md) + - [@ohos.telephony.call](js-apis-call.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 - - [Network Connection Management](js-apis-net-connection.md) - - [Socket Connection](js-apis-socket.md) - - [WebSocket Connection](js-apis-webSocket.md) - - [Data Request](js-apis-http.md) -- Network and Connectivity - - [WLAN](js-apis-wifi.md) - - [Bluetooth](js-apis-bluetooth.md) - - [RPC](js-apis-rpc.md) - - [Upload and Download](js-apis-request.md) -- Device Management - - [Sensor](js-apis-sensor.md) - - [Vibrator](js-apis-vibrator.md) - - [Brightness](js-apis-brightness.md) - - [Battery Info](js-apis-battery-info.md) - - [Power Management](js-apis-power.md) - - [Thermal Management](js-apis-thermal.md) - - [Running Lock](js-apis-runninglock.md) - - [Device Info](js-apis-device-info.md) - - [systemParameter](js-apis-system-parameter.md) - - [Device Management](js-apis-device-manager.md) - - [Window](js-apis-window.md) - - [Display](js-apis-display.md) - - [Update](js-apis-update.md) - - [USB](js-apis-usb.md) - - [Location](js-apis-geolocation.md) + - [@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) + +- Connectivity + + - [@ohos.bluetooth](js-apis-bluetooth.md) + - [@ohos.connectedTag](js-apis-connectedTag.md) + - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.wifi](js-apis-wifi.md) + - [@ohos.wifiext](js-apis-wifiext.md) + - Basic Features - - [Application Context](js-apis-basic-features-app-context.md) - - [Console Logs](js-apis-basic-features-logs.md) - - [Page Routing](js-apis-basic-features-routes.md) - - [Timer](js-apis-basic-features-timer.md) - - [Screen Lock Management](js-apis-screen-lock.md) - - [Setting the System Time](js-apis-system-time.md) - - [Wallpaper](js-apis-wallpaper.md) - - [Pasteboard](js-apis-pasteboard.md) - - [Animation](js-apis-basic-features-animator.md) - - [WebGL](js-apis-webgl.md) - - [WebGL2](js-apis-webgl2.md) - - [Screenshot](js-apis-screenshot.md) - - [Accessibility](js-apis-accessibility.md) -- DFX - - [HiAppEvent](js-apis-hiappevent.md) - - [Performance Tracing](js-apis-hitracemeter.md) - - [Fault Logger](js-apis-faultLogger.md) - - [Distributed Call Chain Tracing](js-apis-hitracechain.md) - - [HiLog](js-apis-hilog.md) - - [HiChecker](js-apis-hichecker.md) - - [HiDebug](js-apis-hidebug.md) + + - [@ohos.accessibility](js-apis-accessibility.md) + - [@ohos.faultLogger](js-apis-faultLogger.md) + - [@ohos.hiAppEvent](js-apis-hiappevent.md) + - [@ohos.hichecker](js-apis-hichecker.md) + - [@ohos.hidebug](js-apis-hidebug.md) + - [@ohos.hilog](js-apis-hilog.md) + - [@ohos.hiTraceChain](js-apis-hitracechain.md) + - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) + - [@ohos.inputMethod](js-apis-inputmethod.md) + - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.pasteboard](js-apis-pasteboard.md) + - [@ohos.screenLock](js-apis-screen-lock.md) + - [@ohos.systemTime](js-apis-system-time.md) + - [@ohos.wallpaper](js-apis-wallpaper.md) + - [Timer](js-apis-timer.md) + +- Device Management + + - [@ohos.batteryInfo ](js-apis-battery-info.md) + - [@ohos.brightness](js-apis-brightness.md) + - [@ohos.deviceInfo](js-apis-device-info.md) + - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) + - [@ohos.geolocation](js-apis-geolocation.md) + - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) + - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) + - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) + - [@ohos.power](js-apis-power.md) + - [@ohos.runningLock](js-apis-runninglock.md) + - [@ohos.sensor](js-apis-sensor.md) + - [@ohos.systemParameter](js-apis-system-parameter.md) + - [@ohos.thermal](js-apis-thermal.md) + - [@ohos.update](js-apis-update.md) + - [@ohos.usb](js-apis-usb.md) + - [@ohos.vibrator](js-apis-vibrator.md) + +- 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 - - [Obtaining Process Information](js-apis-process.md) - - [URL String Parsing](js-apis-url.md) - - [URI String Parsing](js-apis-uri.md) - - [Util](js-apis-util.md) - - [XML Parsing and Generation](js-apis-xml.md) - - [XML-to-JavaScript Conversion](js-apis-convertxml.md) - - [Worker Startup](js-apis-worker.md) - - [Linear Container ArrayList](js-apis-arraylist.md) - - [Linear Container Deque](js-apis-deque.md) - - [Linear Container List](js-apis-list.md) - - [Linear Container LinkedList](js-apis-linkedlist.md) - - [Linear Container Queue](js-apis-queue.md) - - [Linear Container Stack](js-apis-stack.md) - - [Linear Container Vector](js-apis-vector.md) - - [Nonlinear Container HashSet](js-apis-hashset.md) - - [Nonlinear Container HashMap](js-apis-hashmap.md) - - [Nonlinear Container PlainArray](js-apis-plainarray.md) - - [Nonlinear Container TreeMap](js-apis-treemap.md) - - [Nonlinear Container TreeSet](js-apis-treeset.md) - - [Nonlinear Container LightWeightMap](js-apis-lightweightmap.md) - - [Nonlinear Container LightWeightSet](js-apis-lightweightset.md) -- Custom Management - - [Configuration Policy](js-apis-config-policy.md) + - [@ohos.convertxml](js-apis-convertxml.md) + - [@ohos.process](js-apis-process.md) + - [@ohos.uri](js-apis-uri.md) + - [@ohos.url](js-apis-url.md) + - [@ohos.util](js-apis-util.md) + - [@ohos.util.ArrayList](js-apis-arraylist.md) + - [@ohos.util.Deque](js-apis-deque.md) + - [@ohos.util.HashMap](js-apis-hashmap.md) + - [@ohos.util.HashSet](js-apis-hashset.md) + - [@ohos.util.LightWeightMap](js-apis-lightweightmap.md) + - [@ohos.util.LightWeightSet](js-apis-lightweightset.md) + - [@ohos.util.LinkedList](js-apis-linkedlist.md) + - [@ohos.util.List](js-apis-list.md) + - [@ohos.util.PlainArray](js-apis-plainarray.md) + - [@ohos.util.Queue](js-apis-queue.md) + - [@ohos.util.Stack](js-apis-stack.md) + - [@ohos.util.TreeMap](js-apis-treemap.md) + - [@ohos.util.TreeSet](js-apis-treeset.md) + - [@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 + + - [@ohos.bytrace](js-apis-bytrace.md) + - [@system.app](js-apis-system-app.md) + - [@system.battery](js-apis-system-battery.md) + - [@system.brightness](js-apis-system-brightness.md) + - [@system.configuration](js-apis-system-configuration.md) + - [@system.device](js-apis-system-device.md) + - [@system.fetch](js-apis-system-fetch.md) + - [@system.file](js-apis-system-file.md) + - [@system.geolocation](js-apis-system-location.md) + - [@system.mediaquery](js-apis-system-mediaquery.md) + - [@system.network](js-apis-system-network.md) + - [@system.package](js-apis-system-package.md) + - [@system.prompt](js-apis-system-prompt.md) + - [@system.request](js-apis-system-request.md) + - [@system.router](js-apis-system-router.md) + - [@system.sensor](js-apis-system-sensor.md) + - [@system.storage](js-apis-system-storage.md) + - [@system.vibrator](js-apis-system-vibrate.md) + - [console](js-apis-logs.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png b/en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png new file mode 100644 index 0000000000000000000000000000000000000000..6eb89772d315b440636e8ceeda928e5db6b34e40 GIT binary patch literal 9907 zcmb_?XIN8Pw{8LoND%}D=^OVJq(_n7R8$m#D7}WD^eVjsNECsMNKsnoA_CHz^cK2w zCDhQQOAQbp5Fnftzx{ppoaeds{yIOBHOrb~%`xU&W4`YgEBxsbbtZZ)dJqW2^!U+z z9T4c;9iY5SM+N+wB-$PVmkTc+8GC?07uzX6aJ=Y6ZV>1X(Bu1e^?Y%g)A$lI+gJQA z&lv0s>xZ@?3QoX*m7ntK@woiLsfI6ld6EW2?I|WA`R*@xSYCT(-FbcQ&T<&IZm7HjZPyjiSoOZ8x1k~|^RBc0%Av(+d?3{tse zx!l*6L|E_}@M~J}8<l*ZG8$w4JTUs3f;vUNQF$xqse zz3o3zSYh<8bgrhaK~jD(^bo_6poKOBk-YSM=En9Smbev2JS8IKxPx=70NJeyK_|YW zL{{xSl4YxAqm7p)tp^SR)^x@q7{&|+zTQjCmSSHt0veZ z5}tAxR@R|)0^E2xVT0M&WvdGE2C#mD`Y3lrWTS*BFFZ6*I%@_!1d#%?Yyr%^I{ehP zRFtYu^`Y7~s@3zr1AkGL>W}}iaQ}}Q=Jh#rEU=^uu9xA(z*S5MOhZuwC{nC=2L+h_ zf7XmzL4;vlZRLxTB9~j2SqtOJ53}`Z^;;&c>m!7o9UCnwj9-Sg3dzDvL+*_SywTS% zKGDga%Ky3XA-^&9OQ4uL?`8P+CNTKnd0OzpO*IsFlRHjl$>6*?>Jt18>h6TT#wEDk zOBVRKtLLs-b8K?6{H_hFc)OtF-R9dfx#q5O^Zql&*4A*dzBzC|Eo0&^LR{0#5cucF*Rr{&u27!)`}OVc@bWp5d%DczgK3YQ5kb&-j0&8S8%t|=G2Lw2S_!#FivPoOpcHeokZ0)EDZlX(BsD%dX6`dRW178CORtV>~#^{!_wE!tT! zgisWpV%8<=<`|h6@Uj?vplEZnQGO1M^gGVVM(%@cN|ot5EN^9&3$&C zoE07_^(}&=MBSI|8gP)Hp3bd`*m`g3aVvrA9kdX;4M zh5LzSfcexb`2g)xp0{j-{WP)1c@K^s4Ikf1FCSKhP(inoUJx5=n_y{tf}x4*5*SYf z(+d#OILo@+L}RMHS6wp2&Q50j9t##z*gr9aVdp9?g9Xi<&R+$rE^HXR6Wile*o`g? z77`lNjb7%0f9S>LPPOy%3~c(>I zb7TLU;q55mtA;w-KqBF#=1oUF8HXEX8y3Dw&Zx(Hck;nGUXq^jrX&5f?nYOmBAy`e zrA-WwP0r=LRqQlYvjjxYW_DFNJdHfH;8F@2D~q&%O&qpWMxLE4-OIPX2$@(2R3C`4 z;M(i5Qmj^RyWX(#%|T_ckhI*=KqCdq$bOM)$_(B4C9Psr)ULKDdcNNGqa)v}1#(oy zztlvz*?{XLF4MB1lfD=SPcK-S*9y`?JzZ=7;YWNA9ncoXOEPOOgtl zC9SmwYP#+mPOI|I3#g$-58q3GZFZk4w7fgeC%=E3Cptroz4fGmz*3&Pw8{g2OW>(` zp0&g)ecQ(YRqMTpTTvm_>a;NFu614;WP#J@7uQU`)fEiuw>#7s4Sbe@)cjFl6d)v- zuIdkIO37NNhF*KH6g=Ya!O6EMZeE>iwI{b0+#U6EWJL4)hiCPEX17gq)p!1cVHf${ zG9Pp!;N|l7bK`c(ZXvYeuCY~q#(}ZIn7+oiC*1IPB{St;!|^L=7A@SNG0G>0v2!i_ zN0H(3BV$U%+hA=PWb6tq#xMGkvR{h$&=Tcyw9sp*A5VHakvk(+Vtjv@BN5 zm{VNzB+yYy_s^HZBm9X6ivptNr3=^<_#N_LQM}HS@92|&v6|#;okxMPYL3?0O(xD& zf+eT_}ZaRFu`obhdTo7G*)kY_wMI^WF;2&rtx2d!VbIps9ug;i=~ zh3niD-uK!E=X`h6^EElVPhwBLPYWFrup)?OV~LnlNq&~~k_<5o{29C6c4*3>#nEcV z#;U1n#lg@L8)vJ@^lXnAeF8@6Pq>O`6`V(bHcxwzJq`Spk zu>;V@>v*#|>@_#}*r4o6c_lczt@BS+MJ2X*!AlYv6EHYYq8cVn8W?@Jf{*I&); z45nCW-PJbxBv=&xQl&;nLINN97nknT>@+JpXY*AOLU=kKRB^+3T>Q(=?u=&xH18@; z%k{=Ux>Cv6(wM)9_a-UE0=&$SW)L%!$cPoiY$%tzZSDTlH7s^HsXu0u?fl9l5TRhC zGcCvj7M$oRKM&6F)oOZy3YQAFZ2lxC|4D9zxBsCQdU)LT?USVbc;zDpQp$IhlUFaS*EBQBoQ~j~B5@;sXmdRm)1h zDcs#Ws`h4tOgyYC_*XHuv2RzWP)0SOy_US;tO6#}rB3R)vZ)JC37Q88jvGBLldY^9k{kSskpqpoi3dh&@fAsS+ zp@uqtHW5CvM!RXc$)1JozS~S0mMLuJDAGkeo`Q4eZ=J|Ngk^%&>`M61!L(TANbXfv zJU{%Qw&n|y3So6kWynHC;uo@lvA_SW;kQrLQLgin0p<-ABr?6RF3Nb#Lcoy;!p-2z zc9vkU9VgbN6u5@Bxd`!6?YIeGZ~*^sN6PNx7Qfdb`;V7OT!09V6`LbStGVmsi+xkn zP(t&8g@7slG(y!^DFD4W-_700)+@VXIHUCKc9ySH(h3g(KCk&qS~lo1&MlmtRkk_B z<&&MVV=fhRA=0vA-MWafyFR_T$>qjk9#eQ0f%Ni{nfT{G(NV8h`@ZulLa^Zbz95;C zs&8ZEZ)0lcY$6;nDa+s#(Mg}MC1U?A$cuNXcUVtjnxm9u^|y8ahjQ}C`lgYG_L7dhzW#}-j7soi@BLX5EgTn4QwMo4Xvgt ze?bL3pcU(tZKZ>V$o1tq%${x*;7_2Y{zrWeeJ2aUt-mMU;^IqS;_gMlj8PLmoDpCf zDeAs-0Wi&G$^(^oK~lfZU6gT*L6mnbsLkaIE=7b-q-tW-+RxF#e)ucsPfT2zoZF}3 za*XP4PS+Cn}(V)e14$7pc8SQ3KKtq-T1LO}3>VS#rotCYd0EQ0o zC76m4C;JEH%g;YBa!>(EpGIE7EBdH>aSY~w7M+{!zveb>kjWy$ZyB${-W(@VEh1O{ z*#ZBT1Al}WZ3>0SV(wj{5F85A`Au*rOy_^G24|q^Bav`xJ!?3UzvcYIpT`CVyz=$w z0RXWc-*I^)tYr}g!tUr(o}MI(nfm^a!m<*SFoi`h*{}F-6LQtmt&r|Sq)^lj4N zVX$aHK|$Ly+k@K_0&Y$XwP^dhob_Ih+^5U#y^Ae}#c0tT-dj8EElw0oSl}eUNl7H? zp*V?UjC>qh(-}%v$w+eEk72v#WMc#uKoHwOv0md8E?-KR`rg7r1+@UAPO_BGG2NmV zhz=4+1)Z(+VT2gYAMa;B$5!6+S*+;a2@_ zivu8}uc(20N*Q?N-4`XV&E-*usMy`m)eo@Wr2JS4+O>BL1DLz_K1J#OSpGj8^Y=RZ zuCXg(c#c~QInFW~0ZvQRH*^k-2L{$p$}kE{0tNJ2if}pzWy1erx9|Slpt;hah9GWO zn3DI6CYyySev0bWrv~%h#D~nj^AqXTG+Il@zUG8Ka5_4uy;8cZ+|&Dke>6vev3?ER zCqV~kV>K7SX4$vQs7ZP&EVIu{036UYBcP@&$*L+^D8ZvMngf;;pn!v(j(xG2w@Ux9 zxW{pQMc&l%krtFAw9|{Z!e0CuuGF+FRVr=V!60BjsJG^?$}20yOBIkojmT9uBhmOp zPxJAjY?p|9zwuwOC9CDeAMi=;h=dm{aW^x`lgE;VJ5~va9oEc{N%NmRuBg?Sm^-M6 zx1dgf-x1v;LpW@b=8ecFa?JRVUZ0v7J7swkGpB@Xv&a*w7 z8_-p zhOfzK>$aN?2J3!hjl)5L_?IT)slmHRG6By@%*LwXao%pXBRaiGQXglnkM4AeLb+r@ zFK+U~p74+@7X0;9U}7}ELVg32*wqLchCn-|v3YuZ8T0)~#}uC>NfDSLT1nH(?m9dEQpkqJf6lVo{3i^WfWJD__Am>PKQUXt~`)l^LZ$-^?|Ur$n#lnWR*s&Gb#Z zHLi=O)if0^@H#s{f{Zt8M7=U9#RAMxt4*smMICvdSdy>h!CD!g;DRt@YZ z@z;^Ds>*Zq%7XIbRWH1O;#!nUq@iBKgRJANNBV7A3WZ+sJ0t9&1B%67bBa7c0PV8z zqk@JFnW(TV^LOJy!*He>;paXSKTV^CW<-x=taEWRxJY-=_9V+ZAA|r=5_(NDPNCSk zUrH}f-4kG$62H=-RhFb&Boh@a7ouhP zM(M2~(~i@&(`=4tvhSeIm^h{{3*|)zspS3(XBdCek9Y7vhagN%dgJM(%dbGutBrEDoe=-ap)4S4Q3ar&<@&rIH6HOW`Ah zrUS{YNd(KHh47Ll+nV*L0>uHMus+p0P=y#cN3Se7%qw~}wO`b$EGVDd17Qv9+RCoP z<>*{P4|m87BBs44Lw*l)|FNipmUO@~>-0)QMI+=Ze*Ss1f&Y6}H3^-_R1K_?lG`3R z2c+8sGpxm-H$tyAKP5b1;+QNDsv6*6&~>~_EX+=s3imLY8rrH#t>jj$#H=D7Dx60r zhkDnoN+D3I1}d7fDlQ%dDl@kSE8UaxTxwzK=}l!Nf>}`WwYm<}D!mZ`l{fo`G&pDB zgCPQ*Eb|EQz;0?c?{#ez67Kx9$BQ2be@H|_Q;96)tq<~|Is|K9tRdi|3VJ{Hs>gUa z>sGu4ihhL^cG7Uko&`WtIn?Vgvf?;ERnUtRcb_^#K^vrE)VXd-Cb%b9^ zKmL~|!vK`u)uewp+R%WYs{E|c)_psQgPvi0>6*vj`-zeC_w5}0!_>Mn8k_ZU6PNUj zJ`Zn~`O%_DGT(pdA{yK z1J%Ly=}Bkak7=WU&bOS()KN+MRpqspOY^AvoK%AV0Ph@_0Ypk9`EbZz9W2jB6T~ok zH)K*+;6t-2jwnu!`Y(GU776yaqP)9?fT!>uBZe}>nVSSqR(Tt2lU)Cl;k0b2OaZGO z-Y$KttZZ^n#P160uZor}u_4LCa9%Uk<-W;vJmi+z{VpWanIm_rM_Ba<+1<2Dz{(3O zSQhPYaWs35H~R-KFE!NfV82aO$2Ouz7*h5y*zHD`22;nb`{-==jGMfp+LN}e8_uiA zSi7z=cEUx-bgwOGGM2w2X@&86ZQwM+m|z{Vz&er*-Yc&OMIjF7aoi+hBp$&2A>EII~9`B1kl7oJn#qZ=eLz zrt((<6*W)O&k4HoCl?*lm^oHkzXx`CHL;3dAYCAj<-R0ruC^<#Bu1Zx$xwlHt=F-C zzr0vAE0uH*is;el$F8cT!}@X2LR(YLCjC7RlAlyhTp#;lEgieiqe09g&ZHED2$XF( ztL8Q4dKJ15<`Z3>J-SWgCO!+O4x01c80z2gd;WzPGO{n`nzO8!uhBap^x=9!h0Xgq zN!$L`TyOQY$=Ib#oAmg`34+d&81Q7VjP9agd~Vz1LtMNo#@>{eTwle;k2hQ+&9tlP zgB>Ti#X~Z`MkA`m6sOuVYU1lFuYFFaaJh~xIvjQo4A$MBB;>V$-z{OsPN<;7NmZb&5KZcCfI@VxcBn>-UwW>E&Cq&2Fzj*k4C08A$&d zO50BiPWuMLcn>FjeOB9(C$ZghKy5K^9E-WtaGj7JwzZ+rp~S{Wpjc>Q)dIL==k zr@VjLAaH0J2b>fY35MUKf+oP8q$$K_CvMy=VSJI*_JIan*w!?8#SR?GdkG*CCZ5e8 zF$+{Tws)yFu>!=#XT>Sl@D~MiFkFU9nAOB&CvM9zK<4fy06~2UdMLdE7W7?+lr5+A zLxl^`1F#4KWFpLX;8X3)|1IV52Zn-}ey2eoYN({-$cz8#L;;8v5KfWwPmbh2kmO$j z{=eOrVn&EI^M!v){vSvNkcy>2%g*>_alv=Pe^2!Wc)2x%A@@mIUBHn$54;r%1Uvt& z8_ahugvF$sG4?!Ktnm%)+;s}VHTno*vqg(xte9Z|I}g;pQSvhk5WmpweGSRq60-s2 z$ww;{d#rqiS8f3iE|VJi@?V?yn9~}lU!dw6cJllWR;CF34_vzgMD2lDQriB3(*H}{ zKnU|UKKzfke>HeNMag?_jQ2`5r>Zu+oO?|{d}4N}3#&^9ldglepoe(p>giF@w((!U zB95L%|D3SRV5+qa3~bypq6lOc#hBH+6!@t&jB`jF1BcP^tO3 ztG`D8@+jlLq4{HD$WuJ>07DEqMmp2~mVWLk`|zw8$$?H>pz&nnOp%=<fqStW{P- zIV&R4RFUN2@6pJU7pByxBF}@3iG{A{Fm^JN>=X-`n=eebUKTS2xvYJJi+NoxezAc( zuIjh+G!@1IXBPr^h7B#gk`mFAo%Yl<>Y8+^-&9v6{a_V8A~v4|#$SZ{H6AUeFsmHG z<-oj3zT4Y#ZNwP_p4Vr}?I-3HA#Ihv$|`eV>smOodLfKiz`=k|QN#Lxt)z=9>VkToHj;#$ zWQCLXIG2qUclUO80L6BfdOa+%7C#*nr7$5jft+7SGnw=x|GuB!r1M>_@sRR8)~H3* zv!g)*04_*tKsqMg8a>SiPe+oEVm8Z#=kEHN1R~|;V6vA73c5LMa;LiGeLd-ChHM<0 zVgj4}1IItoZT`LK{61{&*1j?%aICTNyI6E2kHc!5Y)*pd7Y=Dj@dN;JK=^J2D1CY+_zf z&nc(4k&L21Sjct1m;AiVqQMIELil;V;+F!*n!5&VErHhi;j+k7i&L%!Me^|WFpJQ) z9|a4w@dJ;&`a>iL;gYRP%a_FGaCWbBJ<#h(ihj({M`FlR;GJ2F)lQf9Sk|;4>G-Dh zL8iwVOBHDf3FLYW_i>^NW&}be*1I6L1m|%t(i1Z0>I3|5A&oV=b;zU3Bi5wj%(j@D;V@Zt z95DaU*r*jJ@AN|%lG*ZJl_@%wh}knD`aTb8DJ_p4l7hNauaV6Mi|e)7d`S4j9=7J&g0twOSUB*{}>Ty!V2Kbm!4)Tln!#v)I2dg~RZ#K8L>Eajc#Pxp+))6w*XTOtn}_0a38 zpDxirR~qqw_(tN)hsUvLfG4uWWrP1$@bWKNx0dNjN4I*}@O5VWG zF)U;;MOgJ^*NfK+xpShaQ*|nn;h3e9~^1Y0Cg< z1d=a?ySZ7!2W*m2E4L7++Rds-3LJq-ngg^^?QXWUl6+JSN%T{o$pkMUFEji2VHA)2 zP^zVf+PB>W-!M?D2!c=~XgRBVyirjpnquMQZ~-E^q%z)lrJ?+YT8{gj#||mJs>~|8 z9H)%2s&GF1`{7lH7c+Esv}uZ(S?OslZDjxnef#;RiwnD}HAR+6iKD|+=h1Z!w4H0( z_3NG+h{9xfy``=s3!hR$>*8yjz=DSzl0lb})s04I`hKPW%%iBE!(LO5XG z@L`W_(DM*n`_E6Ipja^kfgS=xw}4aUrzG;Ix08N|T+h(au{GRrn+PIco{~R)o>O>I z9{ZQE0pg;7XxH%3)_wRG@Lk5?D{5L;;Qk1Z2#vRUspTD~nHsgi3n!)ju;INonkO*s zy|DbHC|S}clVkPKk^dqNXHv^t;74a1h!URBmaoG%5CR;i`wW-_>VYM_XLn)s`ti;6 z?Vmk|eCQa{R?P`zNXE&c&^i}?+Ng3e+9CzIk+sOE3l`j;=tdRn|M>jaFWoS7^_cc? z&ab^xr;Hx1E3|`7jwpNXdom4oZPI}k3AYjd(DF1B4(N&FP4NoPlyCctfPV^)J@3SG zkDbWf2h&m^{fO>V6+8OA6h{8Fqw3$aGUGWJi#^U(2_Jnif93QeMAR=hz97QlhbK%N@n$E*MimS4M{q&Y=SqF&g>S z779o4K{d|1jt#3|Z0tl1-d2kYxzo>ilY7OWCKE71`I1S%#OLwOj4ltBsH`*6At8bdbY-gRfgo+ z;s!*$nk|gQ^}3}sM*EGYJh58ZDo0kUl4++q3&@6*W5j{kG$D8P7)#k5OyHa&L2^y^ zOzCS6W{4_h4}aWWhPgUxCNA@mydZ{!B`)Mc`J+pyJZmKFG5}vn8V^iXK)Na{`jUBZ z+Fi~}3x1V3RTZ?M{cN|O!i~dAsfIAW4j}9!%D=Eq=aITHSY4N8i-ho3GDi zOOHrm_T0@wbbzcdR&$wzo(51$Je2W-M{3Kl&4yG|m099}z zzkT3c7|PZZsOC}jzkO1@h0g+G5-6Y10H7RY%>ZepW*>S^bM^Q -Obtains the application information based on a given bundle name. This method uses a promise to return the result. +Obtains the application information based on a given bundle name. This API uses a promise to return the result. **Required permissions** @@ -37,16 +37,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description| -| ----------- | -------- | +| Type | Description | +| ------------------------- | ------------------ | | Promise\ | Promise used to return the application information.| **Example** @@ -69,7 +69,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId) getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void -Obtains the application information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -81,12 +81,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\ | Yes | Callback used to return the application information. | **Example** @@ -108,7 +108,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId, (err, data) => { getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void -Obtains the application information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -120,11 +120,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\ | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the application information. | **Example** @@ -145,7 +145,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of a specified user in the system. This method uses a promise to return the result. +Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result. **Required permissions** @@ -157,15 +157,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------- | ---- | ----------------------------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ---------- | ---------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| --------------------------- | ----------------------------------- | +| Type | Description | +| --------------------------- | -------------------------- | | Promise> | Promise used to return the information of all available bundles.| **Example** @@ -187,7 +187,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This method uses an asynchronous callback to return the result. +Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. **Required permissions** @@ -199,10 +199,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -222,7 +222,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This method uses an asynchronous callback to return the result. +Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. **Required permissions** @@ -234,11 +234,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -260,7 +260,7 @@ bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Promise\ -Obtains the bundle information based on a given bundle name. This method uses a promise to return the result. +Obtains the bundle information based on a given bundle name. This API uses a promise to return the result. **Required permissions** @@ -272,16 +272,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | BundleOptions | No | Includes **userId**. | +| Name | Type | Mandatory | Description | +| ----------- | ------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| options | BundleOptions | No | Includes **userId**. | **Return value** -| Type | Description | -| -------------------- | ------------------------------------------ | +| Type | Description | +| -------------------- | ---------------------------- | | Promise\ | Promise used to return the bundle information.| **Example** @@ -306,7 +306,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options) getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void -Obtains the bundle information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -318,11 +318,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | **Example** @@ -343,7 +343,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, callback: AsyncCallback\): void -Obtains the bundle information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -355,12 +355,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | BundleOptions | Yes | Includes **userId**. | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| options | BundleOptions | Yes | Includes **userId**. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | **Example** @@ -384,7 +384,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { getAllApplicationInfo(bundleFlags: number, userId?: number): Promise> -Obtains the information about all applications of the specified user. This method uses a promise to return the result. +Obtains the information about all applications of the specified user. This API uses a promise to return the result. **Required permissions** @@ -396,15 +396,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | +| Type | Description | +| -------------------------------- | ------------------------------- | | Promise> | Promise used to return the application information.| **Example** @@ -426,7 +426,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications of the specified user. This method uses an asynchronous callback to return the result. +Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -438,11 +438,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------------------- | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------------------- | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -461,9 +461,9 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ## bundle.getAllApplicationInfo -function getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; +getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; -Obtains the information about all applications. This method uses an asynchronous callback to return the result. +Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -475,10 +475,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------------------- | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------------------- | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -497,7 +497,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { getAbilityInfo(bundleName: string, abilityName: string): Promise\ -Obtains the ability information based on a given want. This method uses a promise to return the result. +Obtains the ability information based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -509,15 +509,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| --------------------- | --------------------- | | Promise\ | Promise used to return the ability information.| **Example** @@ -535,10 +535,9 @@ bundle.getAbilityInfo(bundleName, abilityName) ## bundle.getAbilityInfo -getAbilityInfo(bundleName: string, abilityName: string): callback : -AsyncCallback\: void +getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -550,11 +549,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the ability information.| +| Name | Type | Mandatory | Description | +| ----------- | ------------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| +| callback | AsyncCallback\ | Yes | Callback used to return the ability information.| **Example** @@ -574,7 +573,7 @@ bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { getAbilityLabel(bundleName: string, abilityName: string): Promise\ -Obtains the application name based on a given want. This method uses a promise to return the result. +Obtains the application name based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -586,15 +585,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| ---------------- | ------------------ | | Promise\ | Promise used to return the application name.| **Example** @@ -614,7 +613,7 @@ bundle.getAbilityLabel(bundleName, abilityName) getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallback\): void -Obtains the application name based on a given want. This method uses an asynchronous callback to return the result. +Obtains the application name based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -626,11 +625,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the application name.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------- | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| +| callback | AsyncCallback\ | Yes | Callback used to return the application name. | **Example** @@ -650,7 +649,7 @@ bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { isAbilityEnabled(info: AbilityInfo): Promise\ -Checks whether an ability is enabled based on a given want. This method uses a promise to return the result. +Checks whether an ability is enabled based on a given want. This API uses a promise to return the result. **Required permissions** @@ -662,14 +661,14 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------ | -| info | AbilityInfo | Yes | Ability information. | +| Name | Type | Mandatory | Description | +| ---- | ----------- | ---- | ------------ | +| info | AbilityInfo | Yes | Ability information.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------| +| Type | Description | +| ----------------- | ------------------------- | | Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -691,7 +690,7 @@ bundle.isAbilityEnabled(Info) isAbilityEnabled(info : AbilityInfo, callback : AsyncCallback\): void -Checks whether an ability is enabled based on a given want. This method uses an asynchronous callback to return the result. +Checks whether an ability is enabled based on a given want. This API uses an asynchronous callback to return the result. **Required permissions** @@ -703,10 +702,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| info | AbilityInfo | Yes | Ability information. | -| callback | AsyncCallback\ | Yes| Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | --------------- | +| info | AbilityInfo | Yes | Ability information. | +| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -728,7 +727,7 @@ bundle.isAbilityEnabled(Info, (err, data) => { isApplicationEnabled(bundleName: string): Promise\ -Checks whether an application is enabled based on a given want. This method uses a promise to return the result. +Checks whether an application is enabled based on a given want. This API uses a promise to return the result. **Required permissions** @@ -740,15 +739,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | string | Yes | Bundle name of the application.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------| -| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Type | Description | +| ----------------- | ------------------------- | +| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -766,7 +765,7 @@ bundle.isApplicationEnabled(bundleName) isApplicationEnabled(bundleName: string, callback : AsyncCallback\): void -Checks whether an application is enabled based on a given want. This method uses an asynchronous callback to return the result. +Checks whether an application is enabled based on a given want. This API uses an asynchronous callback to return the result. **Required permissions** @@ -778,15 +777,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| callback | AsyncCallback\ | Yes| Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | --------------- | +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js -let bundleName : "com.example.myapplication"; +let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -800,7 +799,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> -Obtains the ability information based on a given want. This method uses a promise to return the result. +Obtains the ability information based on a given want. This API uses a promise to return the result. **Required permissions** @@ -812,16 +811,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| ---------------------------- | --------------------- | | Promise\>| Promise used to return the ability information.| **Example** @@ -847,7 +846,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\>): void -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. **System capability** @@ -855,12 +854,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------- | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -882,9 +881,9 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { ## bundle.queryAbilityByWant -queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void +queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. **System capability** @@ -892,11 +891,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------- | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -915,98 +914,13 @@ bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { }) ``` -## bundle.getBundleInstaller - -getBundleInstaller(): Promise\ - -Obtains the bundle installer. This method uses a promise to return the result. - -**Required permissions** - -ohos.permission.INSTALL_BUNDLE - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Return value** - -| Type | Description | -| ------------------------ | --------------------------------------------------- | -| Promise\ | Promise used to return the bundle installer.| - -**Example** - -```js -let bundleFilePaths = ['/data/test.hap']; -let param = { - userId : 100, - installFlag : 1, - isKeepData : false -}; -bundle.getBundleInstaller() -.then((installerObject) => { - console.info('Operation successful. '); - installerObject.install(bundleFilePaths, param) - .then((data) => { - console.info('Operation successful. Data:' + JSON.stringify(data)); - }).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); - }) -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - -## bundle.getBundleInstaller - -getBundleInstaller(callback: AsyncCallback\): void; - -Obtains the bundle installer. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.INSTALL_BUNDLE - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ------------------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle installer.| - -**Example** - -```js -let bundleFilePaths = ['/data/test.hap']; -let param = { - userId : 100, - installFlag : 1, - isKeepData : false -}; -bundle.getBundleInstaller((err, installerObject) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - } - console.info('Operation successful. Data:' + JSON.stringify(installerObject)); - installerObject.install(bundleFilePaths, param, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - } - console.info('Operation successful. Data:' + JSON.stringify(data)); - }) -}) -``` ## bundle.getLaunchWantForBundle getLaunchWantForBundle(bundleName: string): Promise\ -Obtains the **Want** object that launches the specified application. This method uses a promise to return the result. +Obtains the **Want** object that launches the specified application. This API uses a promise to return the result. **Required permissions** @@ -1018,13 +932,13 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name of the application.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | string | Yes | Bundle name of the application.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------------------------------ | +| Type | Description | +| -------------- | -------------------------------------- | | Promise\ | Promise used to return the **Want** object.| **Example** @@ -1043,7 +957,7 @@ bundle.getLaunchWantForBundle(bundleName) getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; -Obtains the **Want** object that launches the specified application. This method uses an asynchronous callback to return the result. +Obtains the **Want** object that launches the specified application. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1055,10 +969,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name of the application.| -| callback | AsyncCallback\ | Yes | Callback used to return the **Want** object.| +| Name | Type | Mandatory | Description | +| ---------- | -------------------- | ---- | ------------------------------ | +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the **Want** object.| **Example** @@ -1078,7 +992,7 @@ bundle.getLaunchWantForBundle(bundleName, (err, data) => { getNameForUid(uid: number): Promise\ -Obtains the bundle name based on a UID. This method uses a promise to return the result. +Obtains the bundle name based on a UID. This API uses a promise to return the result. **System capability** @@ -1086,13 +1000,13 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| uid | number | Yes | UID based on which the bundle name is to obtain.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------- | +| uid | number | Yes | UID based on which the bundle name is to obtain.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------------------------------ | +| Type | Description | +| ---------------- | --------------------------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -1109,9 +1023,9 @@ bundle.getNameForUid(uid) ## bundle.getNameForUid8+ -getNameForUid(uid: number, callback: AsyncCallback\): void; +getNameForUid(uid: number, callback: AsyncCallback\) : void -Obtains the bundle name based on a UID. This method uses an asynchronous callback to return the result. +Obtains the bundle name based on a UID. This API uses an asynchronous callback to return the result. **System capability** @@ -1119,10 +1033,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| uid | number | Yes | UID based on which the bundle name is to obtain.| -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------------- | +| uid | number | Yes | UID based on which the bundle name is to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -1140,9 +1054,9 @@ bundle.getNameForUid(uid, (err, data) => { ## bundle.getAbilityIcon8+ -getAbilityIcon(bundleName: string, abilityName: string): Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>; +getAbilityIcon(bundleName: string, abilityName: string): Promise\; -Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This method uses a promise to return the result. +Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -1154,15 +1068,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain.| -| abilityName | string | Yes | Ability name based on which the pixel map is to obtain.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | +| abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | Promise used to return the <[PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| +| Promise\ | Promise used to return the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| **Example** @@ -1179,9 +1093,9 @@ bundle.getAbilityIcon(bundleName, abilityName) ## bundle.getAbilityIcon8+ -getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>): void; +getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This method uses an asynchronous callback to return the result. +Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1193,11 +1107,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain.| -| abilityName | string | Yes | Ability name based on which the pixel map is to obtain.| -| callback | AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | Yes | Callback used to return the <[PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | +| abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| **Example** @@ -1213,172 +1127,44 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { }) ``` - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId?: number): Promise> - -Obtains the extension ability information based on a given want. This method uses a promise to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | - -**Return value** - -| Type | Description | -| ---------------------------- | ---------------------------- | -| Promise> | Promise used to return the extension ability information.| - -**Example** - -```js -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - - - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId: number, callback: AsyncCallback>): void - -Obtains the extension ability information based on a given want. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the extension ability information. | - -**Example** - -```js -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, callback: AsyncCallback>): void; - -Obtains the extension ability information based on a given want. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the extension ability information. | - -**Example** - -```js -let extensionFlags = 0; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - ## ElementName **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | ------ | ---- | ------------------------------------------------------------ | -| deviceId | Read-only | string | No | ID of the device that runs the ability. | -| bundleName | Read-only | string | Yes | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| -| abilityName | Read-only | string | Yes | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| -| uri | Read-only | string | No | Resource ID.| -| shortName | Read-only | string | No | Short name of the **ElementName**.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ---------------------------------------- | +| deviceId | Read-only | string | No | ID of the device that runs the ability. | +| bundleName | Read-only | string | Yes | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| +| abilityName | Read-only | string | Yes | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| +| uri | Read-only | string | No | Resource ID. | +| shortName | Read-only | string | No | Short name of the **ElementName**. | ## InstallErrorCode **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Default Value| Description | -| ------ | ------ | ------ | -| SUCCESS | 0 | Installation succeeded.| -| STATUS_INSTALL_FAILURE | 1 | Installation failed. (The application to be installed does not exist.)| -| STATUS_INSTALL_FAILURE_ABORTED | 2 | Installation aborted.| -| STATUS_INSTALL_FAILURE_INVALID | 3 | Invalid installation parameter.| -| STATUS_INSTALL_FAILURE_CONFLICT | 4 | Installation conflict. (The basic information about the application to upgrade is inconsistent with that of the existing application.)| -| STATUS_INSTALL_FAILURE_STORAGE | 5 | Failed to store the bundle information.| -| STATUS_INSTALL_FAILURE_INCOMPATIBLE | 6 | Installation incompatible. (A downgrade occurs or the signature information is incorrect.)| -| STATUS_UNINSTALL_FAILURE | 7 | Uninstallation failed. (The application to be uninstalled does not exist.)| -| STATUS_UNINSTALL_FAILURE_BLOCKED | 8 | Uninstallation aborted. (This error code is not in use.)| -| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.)| -| STATUS_UNINSTALL_FAILURE_CONFLICT | 10 | Uninstallation conflict. (Failed to uninstall a system application or end the application process.)| -| STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT | 0x0B | Installation failed. (Download timed out.)| -| STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED | 0x0C | Installation failed. (Download failed.)| -| STATUS_RECOVER_FAILURE_INVALID8+ | 0x0D | Failed to restore the pre-installed application.| -| STATUS_ABILITY_NOT_FOUND | 0x40 | Ability not found.| -| STATUS_BMS_SERVICE_ERROR | 0x41 | BMS service error.| -| STATUS_FAILED_NO_SPACE_LEFT8+ | 0x42 | Insufficient device space.| -| STATUS_GRANT_REQUEST_PERMISSIONS_FAILED8+ | 0x43 | Application authorization failed.| -| STATUS_INSTALL_PERMISSION_DENIED8+ | 0x44 | Installation permission denied.| -| STATUS_UNINSTALL_PERMISSION_DENIED8+ | 0x45 | Uninstallation permission denied.| +| Name | Default Value | Description | +| ---------------------------------------- | ---- | ------------------------- | +| SUCCESS | 0 | Installation succeeded. | +| STATUS_INSTALL_FAILURE | 1 | Installation failed. (The application to be installed does not exist.) | +| STATUS_INSTALL_FAILURE_ABORTED | 2 | Installation aborted. | +| STATUS_INSTALL_FAILURE_INVALID | 3 | Invalid installation parameter. | +| STATUS_INSTALL_FAILURE_CONFLICT | 4 | Installation conflict. (The basic information about the application to upgrade is inconsistent with that of the existing application.) | +| STATUS_INSTALL_FAILURE_STORAGE | 5 | Failed to store the bundle information. | +| STATUS_INSTALL_FAILURE_INCOMPATIBLE | 6 | Installation incompatible. (A downgrade occurs or the signature information is incorrect.) | +| STATUS_UNINSTALL_FAILURE | 7 | Uninstallation failed. (The application to be uninstalled does not exist.) | +| STATUS_UNINSTALL_FAILURE_BLOCKED | 8 | Uninstallation aborted. (This error code is not in use.) | +| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.) | +| STATUS_UNINSTALL_FAILURE_CONFLICT | 10 | Uninstallation conflict. (Failed to uninstall a system application or end the application process.)| +| STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT | 0x0B | Installation failed. (Download timed out.) | +| STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED | 0x0C | Installation failed. (Download failed.) | +| STATUS_RECOVER_FAILURE_INVALID8+ | 0x0D | Failed to restore the pre-installed application. | +| STATUS_ABILITY_NOT_FOUND | 0x40 | Ability not found. | +| STATUS_BMS_SERVICE_ERROR | 0x41 | BMS service error. | +| STATUS_FAILED_NO_SPACE_LEFT8+ | 0x42 | Insufficient device space. | +| STATUS_GRANT_REQUEST_PERMISSIONS_FAILED8+ | 0x43 | Application authorization failed. | +| STATUS_INSTALL_PERMISSION_DENIED8+ | 0x44 | Installation permission denied. | +| STATUS_UNINSTALL_PERMISSION_DENIED8+ | 0x45 | Uninstallation permission denied. | ## BundleFlag @@ -1386,21 +1172,20 @@ Enumerates bundle flags. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Default Value| Description | -| ------ | ------ | ------ | -| GET_BUNDLE_DEFAULT | 0x00000000 | Obtains the default application information.| -| GET_BUNDLE_WITH_ABILITIES | 0x00000001 | Obtains the bundle information with the ability information.| -| GET_ABILITY_INFO_WITH_PERMISSION | 0x00000002 | Obtains the ability information with the permission information.| -| GET_ABILITY_INFO_WITH_APPLICATION | 0x00000004 | Obtains the ability information with the application information.| -| GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | Obtains the application information with the permission information.| -| GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | Obtains the bundle information with the information about the required permissions.| -| GET_ABILITY_INFO_WITH_METADATA8+ | 0x00000020 | Obtains the ability metadata information.| -| GET_BUNDLE_WITH_EXTENSION_ABILITY9+ | 0x00000020 | Obtains the bundle information with the extension ability information.| -| GET_APPLICATION_INFO_WITH_METADATA8+ | 0x00000040 | Obtains the application metadata information.| +| Name | Default Value | Description | +| ---------------------------------------- | ---------- | ------------------- | +| GET_BUNDLE_DEFAULT | 0x00000000 | Obtains the default application information. | +| GET_BUNDLE_WITH_ABILITIES | 0x00000001 | Obtains the bundle information with the ability information. | +| GET_ABILITY_INFO_WITH_PERMISSION | 0x00000002 | Obtains the ability information with the permission information. | +| GET_ABILITY_INFO_WITH_APPLICATION | 0x00000004 | Obtains the ability information with the application information. | +| GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | Obtains the application information with the permission information. | +| GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | Obtains the bundle information with the information about the required permissions. | +| GET_ABILITY_INFO_WITH_METADATA8+ | 0x00000020 | Obtains the ability metadata information. | +| GET_APPLICATION_INFO_WITH_METADATA8+ | 0x00000040 | Obtains the application metadata information. | | GET_ABILITY_INFO_SYSTEMAPP_ONLY8+ | 0x00000080 | Obtains the ability information with information about system applications.| -| GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | Obtains information about disabled abilities.| -| GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | Obtains information about disabled applications.| -| GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information.| +| GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | Obtains information about disabled abilities. | +| GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | Obtains information about disabled applications. | +| GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | ## BundleOptions @@ -1408,9 +1193,9 @@ Describes the bundle options. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| userId | number | Yes| Yes| User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------- | +| userId | number | Yes | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| ## BundleInfo @@ -1418,32 +1203,31 @@ Describes the application bundle information. **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 | Yes | No | Application configuration information. | -| abilityInfos | Array\ | Yes | No | Ability configuration information. | -| reqPermissions | Array\ | Yes | No | Array of the permissions to request from the system. | -| reqPermissionDetails | Array\ | Yes | No | Detailed information of the permissions to request from the system.| -| 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\ | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | cpuAbi information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether to install the bundle 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.| -| reqPermissionStates8+ | Array\ | Yes| No| Permission grant state.| -| extensionAbilityInfo9+ | Array\ | Yes| No| Extended information of the ability.| +| 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 | Yes | No | Application configuration information. | +| abilityInfos | Array\ | Yes | No | Ability configuration information. | +| reqPermissions | Array\ | Yes | No | Array of the permissions to request from the system. | +| reqPermissionDetails | Array\ | Yes | No | Detailed information of the permissions to request from the system.| +| 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\ | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | cpuAbi information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether to install the bundle 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. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | ## ApplicationInfo @@ -1451,31 +1235,28 @@ Describes the application information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | -| icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used by default.| -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. | -| moduleInfos | Array\ | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| customizeData | Map> | Yes | Yes | Custom data of the application. | -| codePath8+ | string | Yes| No| Installation directory of the application.| -| metaData8+ | Map> | Yes| No| Custom metadata of the application.| -| metaData9+ | Map> | Yes| No| Metadata of the application.| -| removable8+ | boolean | Yes| No| Whether the application is removable.| -| accessTokenId8+ | number | Yes| No| Access token ID of the application.| -| uid8+ | number | Yes| No| UID of the application.| -| entityType9+ | string | Yes| No| Entity type of the application.| +| Name | Type | Readable | Writable | Description | +| -------------------------- | ---------------------------------- | ---- | ---- | --------------------- | +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used by default.| +| supportedModes | number | Yes | No | Running modes supported by the application. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application. | +| moduleInfos | Array\ | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map> | Yes | No | Custom metadata of the application. | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | ## ModuleInfo @@ -1483,10 +1264,10 @@ Describes the module information of the application. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| moduleName | string | Yes | No | Module name.| -| moduleSourceDir | string | Yes | No | Installation directory.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------ | ---- | ---- | ---- | +| moduleName | string | Yes | No | Module name.| +| moduleSourceDir | string | Yes | No | Installation directory.| ## CustomizeData @@ -1494,11 +1275,11 @@ Describes the custom metadata. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | ---- | ---------------- | -| name | string | Yes | Yes | Custom metadata name.| -| value | string | Yes | Yes | Custom metadata value. | -| extra8+ | string | Yes | Yes | Custom resources. | +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | -------- | +| name | string | Yes | Yes | Custom metadata name.| +| value | string | Yes | Yes | Custom metadata value. | +| extra8+ | string | Yes | Yes | Custom resources. | ## HapModuleInfo @@ -1507,26 +1288,23 @@ Describes the HAP module information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Module name. | -| description | string | Yes | No | Module description. | -| descriptionId | number | Yes | No | Module description ID. | -| icon | string | Yes | No | Module icon. | -| label | string | Yes | No | Module label. | -| labelId | number | Yes | No | Module label ID. | -| iconId | number | Yes | No | Module icon ID. | -| backgroundImg | string | Yes | No | Module background image. | -| supportedModes | number | Yes | No | Modes supported by the module. | -| reqCapabilities | Array\ | Yes | No | Capabilities required for module running.| -| deviceTypes | Array\ | Yes | No | An array of supported device types.| -| abilityInfo | Array\ | Yes | No | Ability information. | -| moduleName | string | Yes | No | Module name. | -| mainAbilityName | string | Yes | No | Name of the entry ability. | -| installationFree | boolean | Yes | No | Whether installation-free is supported. | -| mainElementName8+ | string | Yes| No| Information about the entry ability.| -| extensionAbilityInfo9+ | Array\ | Yes| No| Extension ability information.| -| metadata9+ | Array\ | Yes| No| Metadata of the ability.| +| Name | Type | Readable | Writable | Description | +| --------------------------------- | ---------------------------- | ---- | ---- | ------------------ | +| name | string | Yes | No | Module name. | +| description | string | Yes | No | Module description. | +| descriptionId | number | Yes | No | Module description ID. | +| icon | string | Yes | No | Module icon. | +| label | string | Yes | No | Module label. | +| labelId | number | Yes | No | Module label ID. | +| iconId | number | Yes | No | Module icon ID. | +| backgroundImg | string | Yes | No | Module background image. | +| supportedModes | number | Yes | No | Modes supported by the module. | +| reqCapabilities | Array\ | Yes | No | Capabilities required for module running. | +| deviceTypes | Array\ | Yes | No | An array of supported device types. | +| abilityInfo | Array\ | Yes | No | Ability information. | +| moduleName | string | Yes | No | Module name. | +| mainAbilityName | string | Yes | No | Name of the entry ability. | +| installationFree | boolean | Yes | No | Whether installation-free is supported. | ## ReqPermissionDetail @@ -1534,11 +1312,11 @@ Describes the detailed information of the permissions to request from the system **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | Yes | Name of the permission to request. | -| reason | string | Yes | Yes | Reason for requesting the permission. | -| usedScene | UsedScene | Yes| Yes| Application scenario and timing for using the permission.| +| Name | Type | Readable | Writable | Description | +| --------- | --------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Name of the permission to request. | +| reason | string | Yes | Yes | Reason for requesting the permission. | +| usedScene | UsedScene | Yes | Yes | Application scenario and timing for using the permission.| ## UsedScene @@ -1546,10 +1324,10 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| abilities | Array\ | Yes | Yes | Abilities that use the permission.| -| when | string | Yes | Yes | Time when the permission is used. | +| Name | Type | Readable | Writable | Description | +| --------- | -------------- | ---- | ---- | ---------------- | +| abilities | Array\ | Yes | Yes | Abilities that use the permission.| +| when | string | Yes | Yes | Time when the permission is used. | ## AbilityInfo @@ -1558,36 +1336,35 @@ Describes the ability information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| bundleName | string | Yes | No | Application bundle name. | -| name | string | Yes | No | Ability name. | -| label | string | Yes | No | Ability name visible to users. | -| description | string | Yes | No | Ability description. | -| icon | string | Yes | No | Index of the ability icon resource file. | -| descriptionId | number | Yes | No | Ability description ID. | -| iconId | number | Yes | No | Ability icon ID. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | -| process | string | Yes | No | Process in which this ability runs. If this parameter is not set, the bundle name is used by default.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to. | -| backgroundModes | number | Yes | No | Background service mode of the ability. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | -| type | AbilityType | Yes | No | Ability type. | -| orientation | DisplayOrientation | Yes | No | Ability display orientation. | -| launchMode | LaunchMode | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| -| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data. | -| writePermission | string | Yes | No | Permission required for writing data to the ability. | -| applicationInfo | ApplicationInfo | Yes | No | Application configuration information. | -| uri | string | Yes | No | URI of the ability. | -| labelId | number | Yes | No | Ability label ID. | -| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | -| metaData8+ | Array\ | Yes| No| Custom information of the ability.| -| metaData9+ | Array\ | Yes| No| Metadata of the ability.| -| enabled8+ | boolean | Yes| No| Whether the ability is enabled.| +| Name | Type | Readable | Writable | Description | +| --------------------- | --------------------- | ---- | ---- | ------------------------ | +| bundleName | string | Yes | No | Application bundle name. | +| name | string | Yes | No | Ability name. | +| label | string | Yes | No | Ability name visible to users. | +| description | string | Yes | No | Ability description. | +| icon | string | Yes | No | Index of the ability icon resource file. | +| descriptionId | number | Yes | No | Ability description ID. | +| iconId | number | Yes | No | Ability icon ID. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| process | string | Yes | No | Process in which this ability runs. If this parameter is not set, the bundle name is used by default.| +| targetAbility | string | Yes | No | Target ability that the ability alias points to. | +| backgroundModes | number | Yes | No | Background service mode of the ability. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | +| type | AbilityType | Yes | No | Ability type. | +| orientation | DisplayOrientation | Yes | No | Ability display orientation. | +| launchMode | LaunchMode | Yes | No | Ability launch mode. | +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| +| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | +| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data. | +| writePermission | string | Yes | No | Permission required for writing data to the ability. | +| applicationInfo | ApplicationInfo | Yes | No | Application configuration information. | +| uri | string | Yes | No | URI of the ability. | +| labelId | number | Yes | No | Ability label ID. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | +| metaData8+ | Array\ | Yes | No | Custom information of the ability. | +| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | ## AbilityType @@ -1595,12 +1372,12 @@ Enumerates ability types. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ------- | ---- | --------------------------- | -| UNKNOWN | None | Unknown ability type. | -| PAGE | None | Ability that has a UI. | -| SERVICE | None | Ability that does not have a UI. | -| DATA | None | Ability that is used to provide data access services.| +| Name | Type | Description | +| ------- | ---- | ----------------- | +| UNKNOWN | None | Unknown ability type. | +| PAGE | None | Ability that has a UI. | +| SERVICE | None | Ability that does not have a UI. | +| DATA | None | Ability that is used to provide data access services.| ## DisplayOrientation @@ -1608,12 +1385,12 @@ Enumerates display orientations. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ------------- | ---- | ------------------------ | -| UNSPECIFIED | None | The system automatically determines the display orientation. | -| LANDSCAPE | None | Landscape orientation. | -| PORTRAIT | None | Portrait orientation. | -| FOLLOW_RECENT | None | The page ability orientation is the same as that of the nearest ability in the stack.| +| Name | Type | Description | +| ------------- | ---- | ------------- | +| UNSPECIFIED | None | The system automatically determines the display orientation. | +| LANDSCAPE | None | Landscape orientation. | +| PORTRAIT | None | Portrait orientation. | +| FOLLOW_RECENT | None | The page ability orientation is the same as that of the nearest ability in the stack.| ## LaunchMode @@ -1621,10 +1398,10 @@ Enumerates launch modes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| SINGLETON | 0 | The ability has only one instance.| -| STANDARD | 1 | The ability can have multiple instances. | +| Name | Type | Description | +| --------- | ---- | ------------- | +| SINGLETON | 0 | The ability has only one instance.| +| STANDARD | 1 | The ability can have multiple instances. | ## AbilitySubType @@ -1632,56 +1409,23 @@ Enumerates ability subtypes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ----------------------------- | -| UNSPECIFIED | 0 | Undefined ability subtype. | +| Name | Type | Description | +| ----------- | ---- | -------------------- | +| UNSPECIFIED | 0 | Undefined ability subtype. | | CA | 1 | Ability that has a UI.| -## ExtensionAbilityType9+ - -Enumerates extension ability types. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type| Description | -| -------------------- | ---- | ----------------------------- | -| FORM9+ | 0 | Form included. | -| WORK_SCHEDULER9+ | 1 | Work scheduler included.| -| INPUT_METHOD9+ | 2 | Input method included. | -| SERVICE9+ | 3 | Service included. | -| ACCESSIBILITY9+ | 4 | Accessibility included. | -| DATA_SHARE9+ | 5 | Data sharing included.| -| FILE_SHARE9+ | 6 | File sharing included.| -| STATIC_SUBSCRIBER9+ | 7 | Subscribers included. | -| WALLPAPER9+ | 8 | Wallpaper included. | -| UNSPECIFIED9+ | 9 | Unspecified type. | - -## ExtensionFlag9+ - -Enumerates extension flags. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Default Value| Description | -| ------ | ------ | ------ | -| GET_EXTENSION_INFO_DEFAULT9+ | 0x00000000 | Obtains the default extension ability information.| -| GET_EXTENSION_INFO_WITH_PERMISSION9+ | 0x00000002 | Obtains the extension ability information that carries permission information.| -| GET_EXTENSION_INFO_WITH_APPLICATION9+ | 0x00000004 | Obtains the extension ability information that carries application information.| -| GET_EXTENSION_INFO_WITH_METADATA9+ | 0x00000020 | Obtains the extension ability information that carries metadata information.| - - ## ColorMode Enumerates color modes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| AUTO_MODE | -1 | Automatic mode.| -| DARK_MODE | 0 | Dark mode. | -| LIGHT_MODE | 1 | Light mode. | +| Name | Type | Description | +| ---------- | ---- | ---- | +| AUTO_MODE | -1 | Automatic mode.| +| DARK_MODE | 0 | Dark mode.| +| LIGHT_MODE | 1 | Light mode.| ## GrantStatus @@ -1690,44 +1434,7 @@ Enumerates permission grant statuses. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| PERMISSION_DENIED | -1 | Permission denied.| -| PERMISSION_GRANTED | 0 | Permission granted. | - - -## ExtensionAbilityInfo9+ - -Describes the extension ability information. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| bundleName9+ | string | Yes | No | Application bundle name. | -| moduleName9+ | string | Yes | No | Name of the HAP file to which the extension ability belongs. | -| name9+ | string | Yes | No | Name of the extension ability. | -| labelId9+ | number | Yes | No | Label ID of the extension ability. | -| descriptionId9+ | number | Yes | No | Description ID of the extension ability. | -| iconId9+ | number | Yes | No | Icon ID of the extension ability. | -| isVisible9+ | boolean | Yes | No | Whether the extension ability can be called by other applications. | -| extensionAbilityType9+ | bundle.ExtensionAbilityType | Yes | No | Type of the extension ability. | -| permissions9+ | Array\ | Yes | No | Permissions required for other applications to call the extension ability.| -| applicationInfo9+ | ApplicationInfo | Yes | No | Application configuration information. | -| metaData9+ | Array\ | Yes| No| Metadata of the extension ability.| -| enabled9+ | boolean | Yes| No| Whether the extension ability is enabled.| -| readPermission9+ | string | Yes | No | Permission required for reading the extension ability data. | -| writePermission9+ | string | Yes | No | Permission required for writing data to the extension ability. | - - -## Metadata9+ - -Describes the metadata information. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | ---- | ---------------- | -| name9+ | string | Yes | Yes | Metadata name.| -| value9+ | string | Yes | Yes | Metadata value. | -| resource9+ | string | Yes | Yes | Metadata resource. | +| Name | Type | Description | +| ------------------ | ---- | ---- | +| PERMISSION_DENIED | -1 | Permission denied.| +| PERMISSION_GRANTED | 0 | Permission granted. | diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 4b2526ce83..7beee10809 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -880,9 +880,9 @@ Obtains the context of the application. **Return value** -| Parameters | Type | Description | -| --------------- | ------------------------- |------ | -| Context | Context |Application context.| +| Type | Description | +| --------- |------ | +| Context |Application context.| **Example** @@ -908,7 +908,7 @@ var context = featureAbility.getContext().getApplicationContext(); | ----------- | -------- | -------------- | ---- | ------------------ | | requestCode | Read-only | number | Yes | Request code passed.| | permissions | Read-only | Array\ | Yes | Permissions requested. | -| authResults | Read-only | Array\ | Yes | Permission request result. | +| authResults | Read-only | Array\ | Yes | Permission request result. | ## HapModuleInfo diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md deleted file mode 100644 index 6e5f9e4b36..0000000000 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ /dev/null @@ -1,495 +0,0 @@ -# AbilityContext - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements the ability context. This module is inherited from **Context**. - - -## Usage - - -Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. - - - -```js -import Ability from '@ohos.application.Ability' -class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - let context = this.context; - } -} -``` - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityContext.startAbility - -startAbility(want: Want, callback: AsyncCallback<void>): void - -Starts an ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - this.context.startAbility(want, (error) => { - console.log("error.code = " + error.code) - }) - ``` - - -## AbilityContext.startAbility - -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void - -Starts an ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) - ``` - - -## AbilityContext.startAbility - -startAbility(want: Want, options?: StartOptions): Promise<void>; - -Starts an ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options) - .then((data) => { - console.log('Operation successful.') - }).catch((error) => { - console.log('Operation failed.'); - }) - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| - - -**Example** - - ```js - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| - - -**Example** - - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; - -Starts an ability. This API uses a promise to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| - - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| - -**Example** - - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { - console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) - }, (error) => { - console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) - }) - ``` - - -## AbilityContext.terminateSelf - -terminateSelf(callback: AsyncCallback<void>): void; - -Terminates this ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); - ``` - - -## AbilityContext.terminateSelf - -terminateSelf(): Promise<void>; - -Terminates this ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; - -Terminates this ability. This API uses a callback to return the information to the caller of **startAbilityForResult**. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }, (error) => { - console.log("terminateSelfWithResult is called = " + error.code) - } - ); - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult): Promise<void>; - -Terminates this ability. This API uses a promise to return information to the caller of **startAbilityForResult**. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }).then((result) => { - console.log("terminateSelfWithResult") - } - ) - ``` - - -## AbilityContext.startAbilityByCall - -startAbilityByCall(want: Want): Promise<Caller>; - -Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<Caller> | Promise used to return the caller object to communicate with.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - console.log('Caller GetCaller Get ' + call); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a pop-up window. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| - | callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ``` - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); - }); - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a pop-up window. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ``` - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` - - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string, callback:AsyncCallback<void>): void; - -Sets the label of the ability displayed in the task. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); - }); - ``` - - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string): Promise<void> - -Sets the label of the ability displayed in the task. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.setMissionLabel("test").then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md new file mode 100644 index 0000000000..e81e9d60f6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -0,0 +1,25 @@ +# ErrorCode + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import errorCode from '@ohos.ability.errorCode' +``` + +## ErrorCode + +Defines the error code used when the ability is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| NO_ERROR | 0 | No error occurs. | +| INVALID_PARAMETER | -1 | Invalid parameter.| +| ABILITY_NOT_FOUND | -2 | The ability is not found.| +| PERMISSION_DENY | -3 | Permission denied. | diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md new file mode 100644 index 0000000000..ef6e3e6001 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -0,0 +1,88 @@ +# wantConstant + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import wantConstant from '@ohos.ability.wantConstant' +``` + + +## wantConstant.Action + +**System capability**: SystemCapability.Ability.AbilityBase + +Lists the permissions. + +| Common Event Macro | Common Event Name | Subscriber Permission | +| ------------ | ------------------ | ---------------------- | +| ACTION_HOME | ohos.want.action.home | None | +| ACTION_DIAL | ohos.want.action.dial | None | +| ACTION_SEARCH | ohos.want.action.search | None | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None | +| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | +| ACTION_SET_ALARM | ohos.want.action.setAlarm | None | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None | +| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None | +| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None | +| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None | +| ACTION_SEND_SMS | ohos.want.action.sendSms | None | +| ACTION_CHOOSE | ohos.want.action.choose | None | +| ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | None | +| ACTION_VIDEO_CAPTUR8+ | ohos.want.action.videoCapture | None | +| ACTION_SELECT | ohos.want.action.select | None | +| ACTION_SEND_DATA | ohos.want.action.sendData | None | +| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None | +| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None | +| ACTION_VIEW_DATA | ohos.want.action.viewData | None | +| ACTION_EDIT_DATA | ohos.want.action.editData | None | +| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None | +| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None | +| ACTION_FILE_SELECT7+ | ohos.action.fileSelect | None | +| PARAMS_STREAM7+ | ability.params.stream | None | +| ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | None | + + +## wantConstant.Entity + +**System capability**: SystemCapability.Ability.AbilityBase + +Lists the permissions. + +| Common Event Macro | Common Event Name | Subscriber Permission | +| ------------ | ------------------ | ---------------------- | +| ENTITY_DEFAULT | entity.system.default | None | +| ENTITY_HOME | entity.system.homel | None | +| ENTITY_VOICE | ENTITY_VOICE | None | +| ENTITY_BROWSABLE | entity.system.browsable | None | +| ENTITY_VIDEO | entity.system.video | None | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | + + +## flags + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 0d008c7f83..9f81d3aab8 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -204,6 +204,8 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS + **System capability**: SystemCapability.Security.AccessToken **Parameters** @@ -234,7 +236,7 @@ promise.then(data => { Enumerates the permission grant states. -**System capability:** SystemCapability.Security.AccessToken +**System capability**: SystemCapability.Security.AccessToken | Name | Default Value | Description | | ----------------------------- | ---------------------- | ----------------------- | diff --git a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md new file mode 100644 index 0000000000..5f772d8706 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @@ -0,0 +1,76 @@ +# AbilityDelegatorRegistry + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityLifecycleState + +Enumerates the ability lifecycle states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | ---- | --------------------------- | +| UNINITIALIZED | 0 | The ability is in an invalid state. | +| CREATE | 1 | The ability is created.| +| FOREGROUND | 2 | The ability is running in the foreground. | +| BACKGROUND | 3 | The ability is running in the background. | +| DESTROY | 4 | The ability is destroyed.| + + + +## AbilityDelegatorRegistry.getAbilityDelegator + +getAbilityDelegator(): AbilityDelegator + +Obtains the **AbilityDelegator** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| + +**Example** + +```js +var abilityDelegator; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +``` + + + +## AbilityDelegatorRegistry.getArguments + +getArguments(): AbilityDelegatorArgs + +Obtains the **AbilityDelegatorArgs** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| + +**Example** + +```js +var args = AbilityDelegatorRegistry.getArguments(); +console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments testCaseNames:" + args.testCaseNames); +console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md index 0ed9eb40d2..b4f137e8d3 100644 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md @@ -22,6 +22,7 @@ abilitymanager.getAbilityRunningInfos((err,data) => { ``` ## Attributes + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Readable| Writable| Description| @@ -31,10 +32,11 @@ abilitymanager.getAbilityRunningInfos((err,data) => { | uid | number | Yes| No| User ID. | | processName | string | Yes| No| Process name. | | startTime | number | Yes| No| Ability start time. | -| abilityState | [abilityManager.AbilityState](#abilitymanager-abilitystate) | Yes| No| Ability state. | +| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | Yes| No| Ability state. | ## abilityManager.AbilityState + Enumerates the ability states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md b/en/application-dev/reference/apis/js-apis-abilitystagecontext.md deleted file mode 100644 index 91e8a7513e..0000000000 --- a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md +++ /dev/null @@ -1,33 +0,0 @@ -# AbilityStageContext - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md). - - -## Usage - - -The ability stage context is obtained through an **AbilityStage** instance. - - - -```js -import AbilityStage from '@ohos.application.AbilityStage'; -class MyAbilityStage extends AbilityStage { - onCreate() { - let abilityStageContext = this.context; - } -} -``` - - -## Attributes -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index f8414adaa9..7041eaef27 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -20,8 +20,8 @@ Creates an **AppAccountManager** instance. **System capability**: SystemCapability.Account.AppAccount **Return Value** -| Type | Description | -| ----------------- | ------------------------ | +| Type | Description | +| ----------------- | ------------ | | AppAccountManager | **AppAccountManager** instance created.| **Example** @@ -43,10 +43,10 @@ Adds an app account to the account management service. This method uses an async **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------------- | +| name | string | Yes | Name of the app account to add. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| **Example** @@ -67,11 +67,11 @@ Adds an app account and its additional information to the account management ser **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information (for example, token) of the app account to add. The additional information cannot contain sensitive information about the app account.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account and its additional information are added. | +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| name | string | Yes | Name of the app account to add. | +| extraInfo | string | Yes | Additional information (for example, token) of the app account to add. The additional information cannot contain sensitive information about the app account.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account and its additional information are added. | **Example** @@ -94,15 +94,15 @@ Adds an app account and its additional information to the account management ser **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information of the app account to add. The additional information cannot contain sensitive information about the app account.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------------------------------- | +| name | string | Yes | Name of the app account to add. | +| extraInfo | string | Yes | Additional information of the app account to add. The additional information cannot contain sensitive information about the app account.| **Return Value** -| Type | Description | -| ------------------- | ---------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -126,12 +126,12 @@ Implicitly adds an app account based on the specified account owner, authenticat **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------ | -| owner | string | Yes | Bundle name of the app account to add.| -| authType | string | Yes | Authentication type of the app account to add. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| owner | string | Yes | Bundle name of the app account to add.| +| authType | string | Yes | Authentication type of the app account to add. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** @@ -167,10 +167,10 @@ Deletes an app account from the account management service. This method uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------- | -| name | string | Yes | Name of the app account to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the app account to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| **Example** @@ -191,14 +191,14 @@ Deletes an app account from the account management service. This method uses a p **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------ | -| name | string | Yes | Name of the app account to delete.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| name | string | Yes | Name of the app account to delete.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -222,11 +222,11 @@ Disables an app account from accessing an application with the given bundle name **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name.| **Example** @@ -247,15 +247,15 @@ Disables an app account from accessing an application with the given bundle name **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ---------------------------------- | -| name | string | Yes | App account name.| -| bundleName | string | Yes | Bundle name of an app. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ----------------- | +| name | string | Yes | App account name.| +| bundleName | string | Yes | Bundle name of an app. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -279,11 +279,11 @@ Enables an app account to access an application with the given bundle name. This **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name.| **Example** @@ -304,15 +304,15 @@ Enables an app account to access an application with the given bundle name. This **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -337,10 +337,10 @@ Checks whether an app account allows application data synchronization. This meth **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | -------------------------------------------- | -| name | string | Yes | App account name. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the app account allows application data synchronization.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------- | +| name | string | Yes | App account name. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the app account allows application data synchronization.| **Example** @@ -364,14 +364,14 @@ Checks whether an app account allows application data synchronization. This meth **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | string | Yes | App account name.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | App account name.| **Return Value** -| Type | Description | -| :--------------------- | :---------------------------------- | +| Type | Description | +| :--------------------- | :-------------------- | | Promise<boolean> | Promise used to return the result.| **Example** @@ -387,7 +387,7 @@ Checks whether an app account allows application data synchronization. This meth ### setAccountCredential -setAccountCredential(name: string, credentialType: string, credential: string callback: AsyncCallback<void>): void +setAccountCredential(name: string, credentialType: string, credential: string, callback: AsyncCallback<void>): void Sets a credential for an app account. This method uses an asynchronous callback to return the result. @@ -395,12 +395,12 @@ Sets a credential for an app account. This method uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | ---------------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to set. | -| credential | string | Yes | Credential to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when a credential is set for the specified app account.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ---- | -------------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to set. | +| credential | string | Yes | Credential to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when a credential is set for the specified app account.| **Example** @@ -421,16 +421,16 @@ Sets a credential for an app account. This method uses a promise to return the r **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to set.| -| credential | string | Yes | Credential to set. | +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to set.| +| credential | string | Yes | Credential to set. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -454,11 +454,11 @@ Sets additional information for an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | -------------------------------- | -| name | string | Yes | App account name. | -| extraInfo | string | Yes | Additional information to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when additional information is set for the specified app account.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------- | +| name | string | Yes | App account name. | +| extraInfo | string | Yes | Additional information to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when additional information is set for the specified app account.| **Example** @@ -479,15 +479,15 @@ Sets additional information for an app account. This method uses a promise to re **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------ | -| name | string | Yes | App account name. | -| extraInfo | string | Yes | Additional information to set.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | --------- | +| name | string | Yes | App account name. | +| extraInfo | string | Yes | Additional information to set.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -513,11 +513,11 @@ Sets whether to enable application data synchronization for an app account. This **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------------------------------------- | -| name | string | Yes | App account name. | -| isEnable | boolean | Yes | Whether to enable app data synchronization. | -| callback | AsyncCallback<void> | Yes | Callback invoked when application data synchronization is enabled or disabled for the app account.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | App account name. | +| isEnable | boolean | Yes | Whether to enable app data synchronization. | +| callback | AsyncCallback<void> | Yes | Callback invoked when application data synchronization is enabled or disabled for the app account.| **Example** @@ -540,15 +540,15 @@ Sets whether to enable application data synchronization for an app account. This **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| isEnable | boolean | Yes | Whether to enable app data synchronization.| +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | App account name. | +| isEnable | boolean | Yes | Whether to enable app data synchronization.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -572,12 +572,12 @@ Sets data to be associated with an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to set. The private key can be customized.| +| value | string | Yes | Value of the data to be set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| **Example** @@ -597,16 +597,16 @@ Sets data to be associated with an app account. This method uses a promise to re **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to set. The private key can be customized.| +| value | string | Yes | Value of the data to be set. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -630,11 +630,11 @@ Obtains the credential of an app account. This method uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | --------------------------- | ---- | ---------------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential of the specified app account.| +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential of the specified app account.| **Example** @@ -656,15 +656,15 @@ Obtains the credential of an app account. This method uses a promise to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to obtain.| +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to obtain.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -688,10 +688,10 @@ Obtains additional information of an app account. This method uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------------------- | -| name | string | Yes | App account name. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ---------------- | +| name | string | Yes | App account name. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| **Example** @@ -713,14 +713,14 @@ Obtains additional information of an app account. This method uses a promise to **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | string | Yes | App account name.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | App account name.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -744,11 +744,11 @@ Obtains data associated with an app account. This method uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| **Example** @@ -770,15 +770,15 @@ Obtains data associated with an app account. This method uses a promise to retur **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to obtain.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -798,15 +798,15 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>& Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------- | -| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------- | +| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| **Example** @@ -824,14 +824,14 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<AppAccountInfo>> | Promise used to return the result.| **Example** @@ -851,16 +851,16 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------- | -| owner | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------- | +| owner | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| **Example** @@ -879,20 +879,20 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------- | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<AppAccountInfo>> | Promise used to return the result.| **Example** @@ -917,11 +917,11 @@ Subscribes to the account change event of the specified account owners. This met **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | 'change' | Yes | Type of the event to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| -| owners | Array<string> | Yes | Owners of the accounts. | -| callback | Callback<Array<AppAccountInfo>> | Yes | Callback invoked to return the account change. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'change' | Yes | Type of the event to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| +| owners | Array<string> | Yes | Owners of the accounts. | +| callback | Callback<Array<AppAccountInfo>> | Yes | Callback invoked to return the account change. | **Example** @@ -948,10 +948,10 @@ Unsubscribes from the account change event. This method uses an asynchronous cal **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | ------------------------ | -| type | 'change' | Yes | Account change event to unsubscribe from. | -| callback | Callback> | No | Callback used to report the account change.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'change' | Yes | Account change event to unsubscribe from. | +| callback | Callback> | No | Callback used to report the account change.| **Example** @@ -981,13 +981,13 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------ | -| name | string | Yes | Name of the app account to authenticate. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the app account to authenticate. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** @@ -1023,12 +1023,12 @@ Obtains the OAuth access token of an app account based on the specified authenti **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | **Example** @@ -1050,16 +1050,16 @@ Obtains the OAuth access token of an app account based on the specified authenti **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | **Parameters** -| Type | Description | -| --------------------- | ----------------------------------- | +| Type | Description | +| --------------------- | --------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -1083,12 +1083,12 @@ Sets an OAuth access token for an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | App account name.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------- | +| name | string | Yes | App account name.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -1109,16 +1109,16 @@ Sets an OAuth access token for an app account. This method uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------- | -| name | string | Yes | App account name.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| name | string | Yes | App account name.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to set.| **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -1142,13 +1142,13 @@ Deletes the specified OAuth access token for an app account. This method uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to delete.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -1169,17 +1169,17 @@ Deletes the specified OAuth access token for an app account. This method uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to delete.| **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -1203,13 +1203,13 @@ Sets the visibility of an OAuth access token to the specified app. This method u **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------ | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -1230,24 +1230,23 @@ Sets the visibility of an OAuth access token to the specified app. This method u **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- | ------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ------------ | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** ``` const appAccountManager = account_appAccount.createAppAccountManager(); - const appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { @@ -1265,12 +1264,12 @@ Checks whether an OAuth token is visible to the specified app. This method uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------- | ---- | -------------------------- | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------- | ---- | ------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1292,16 +1291,16 @@ Checks whether an OAuth token is visible to the specified app. This method uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ---------------------- | ----------------------------------- | +| Type | Description | +| ---------------------- | --------------------- | | Promise<boolean> | Promise used to return the result.| **Example** @@ -1325,11 +1324,11 @@ Obtains information about all OAuth access tokens of an app account visible to t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<Array<OAuthTokenInfo>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<Array<OAuthTokenInfo>> | Yes | Callback invoked to return the result. | **Example** @@ -1351,15 +1350,15 @@ Obtains information about all OAuth access tokens of an app account visible to t **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<OAuthTokenInfo>> | Promise used to return the result.| **Example** @@ -1383,11 +1382,11 @@ Obtains the authorization list of OAuth access tokens of an app account. This me **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | **Example** @@ -1409,15 +1408,15 @@ Obtains the authorization list of OAuth access tokens of an app account. This me **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ---------------------------------- | ----------------------------------- | +| Type | Description | +| ---------------------------------- | --------------------- | | Promise<Array<string>> | Promise used to return the result.| **Example** @@ -1441,10 +1440,10 @@ Obtains the authenticator callback for a session. This method uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------ | ---- | ---------------- | -| sessionId | string | Yes | ID of the session to authenticate.| -| callback | AsyncCallback<AuthenticatorCallback> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the session to authenticate.| +| callback | AsyncCallback<AuthenticatorCallback> | Yes | Callback invoked to return the result.| **Example** @@ -1476,14 +1475,14 @@ Obtains the authenticator callback for a session. This method uses a promise to **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------------- | -| sessionId | string | Yes | ID of the session to authenticate.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the session to authenticate.| **Parameters** -| Type | Description | -| ------------------------------------ | ----------------------------------- | +| Type | Description | +| ------------------------------------ | --------------------- | | Promise<AuthenticatorCallback> | Promise used to return the result.| **Example** @@ -1516,10 +1515,10 @@ Obtains authenticator information of an app account. This method uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<AuthenticatorInfo> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<AuthenticatorInfo> | Yes | Callback invoked to return the result. | **Example** @@ -1541,14 +1540,14 @@ Obtains authenticator information of an app account. This method uses a promise **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| -------------------------------- | ----------------------------------- | +| Type | Description | +| -------------------------------- | --------------------- | | Promise<AuthenticatorInfo> | Promise used to return the result.| **Example** @@ -1568,10 +1567,10 @@ Defines app account information. **System capability**: SystemCapability.Account.AppAccount -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| -| name | string | Yes | App account name. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| name | string | Yes | App account name. | ## OAuthTokenInfo8+ @@ -1579,10 +1578,10 @@ Defines OAuth access token information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------- | -| authType | string | Yes | Authentication type.| -| token | string | Yes | Value of the access token. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| authType | string | Yes | Authentication type.| +| token | string | Yes | Value of the access token. | ## AuthenticatorInfo8+ @@ -1590,11 +1589,11 @@ Defines OAuth authenticator information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------- | -| owner | string | Yes | Bundle name of the authenticator owner.| -| iconId | string | Yes | ID of the authenticator icon. | -| labelId | string | Yes | ID of the authenticator label. | +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| owner | string | Yes | Bundle name of the authenticator owner.| +| iconId | string | Yes | ID of the authenticator icon. | +| labelId | string | Yes | ID of the authenticator label. | ## Constants8+ @@ -1602,19 +1601,19 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ------------------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation for implicitly adding an account. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | +| Name | Default Value | Description | +| ----------------------------- | ---------------------- | ------------- | +| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation for implicitly adding an account. | +| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | +| KEY_NAME | "name" | App account name. | | KEY_OWNER | "owner" | App account owner.| -| KEY_TOKEN | "token" | OAuth access token. | -| KEY_ACTION | "action" | Action. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | Caller process ID (PID). | -| KEY_CALLER_UID | "callerUid" | Caller user ID (UID). | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Caller bundle name. | +| KEY_TOKEN | "token" | OAuth access token. | +| KEY_ACTION | "action" | Action. | +| KEY_AUTH_TYPE | "authType" | Authentication type. | +| KEY_SESSION_ID | "sessionId" | Session ID. | +| KEY_CALLER_PID | "callerPid" | Caller process ID (PID). | +| KEY_CALLER_UID | "callerUid" | Caller user ID (UID). | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Caller bundle name. | ## ResultCode8+ @@ -1622,27 +1621,27 @@ Enumerates the result codes. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value| Description | -| ----------------------------------- | ------ | ------------------------ | -| SUCCESS | 0 | The operation is successful. | -| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | -| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | -| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | -| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | -| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | -| ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. | -| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. | -| ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. | -| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. | -| ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. | -| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | -| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | -| ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | -| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth access token does not exist.| -| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth access tokens reaches the limit. | -| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | -| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | -| ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | +| Name | Default Value | Description | +| ----------------------------------- | ----- | ------------ | +| SUCCESS | 0 | The operation is successful. | +| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | +| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | +| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | +| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | +| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | +| ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. | +| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. | +| ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. | +| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. | +| ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. | +| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | +| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | +| ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | +| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth access token does not exist.| +| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth access tokens reaches the limit. | +| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | +| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | +| ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | ## AuthenticatorCallback8+ @@ -1657,10 +1656,10 @@ Called back to send the authentication result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------------------- | ---- | ------------ | -| code | number | Yes | Authentication result code.| -| result | {[key: string]: any} | Yes | Authentication result. | +| Name | Type | Mandatory | Description | +| ------ | -------------------- | ---- | ------ | +| code | number | Yes | Authentication result code.| +| result | {[key: string]: any} | Yes | Authentication result. | **Example** @@ -1687,9 +1686,9 @@ Called back to redirect an authentication request. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type| Mandatory| Description | -| ------- | ---- | ---- | -------------------- | -| request | Want | Yes | Request to be redirected.| +| Name | Type | Mandatory | Description | +| ------- | ---- | ---- | ---------- | +| request | Want | Yes | Request to be redirected.| **Example** @@ -1724,12 +1723,12 @@ Implicitly adds an app account based on the specified authentication type and op **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------- | ---- | ------------------------------ | -| authType | string | Yes | Authentication type. | -| callerBundleName | string | Yes | Bundle name of the authentication requester. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Bundle name of the authentication requester. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| ### authenticate8+ @@ -1740,13 +1739,13 @@ Authenticates an app account to obtain the OAuth access token. This method uses **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------- | ---- | ------------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| callerBundleName | string | Yes | Bundle name of the authentication requester. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Bundle name of the authentication requester. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md index fffd17605b..21cff7a9c8 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -1,8 +1,8 @@ # MissionSnapshot -> **NOTE** -> The initial APIs of this module are supported since API 8. +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Provides snapshot of a mission. @@ -10,8 +10,6 @@ Provides snapshot of a mission. ## Modules to Import -Import ElementName and image before use. - ``` import { ElementName } from '../bundle/elementName'; diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md new file mode 100644 index 0000000000..3731cf8c99 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -0,0 +1,30 @@ +# Want + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**Want** is the basic communication component of the system. + + +## Modules to Import + + +``` +import Want from '@ohos.application.Want'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read only | string | No | ID of the device running the ability. | +| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | +| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| +| action | Read only | string | No | Action option. | +| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read only | Array\ | No | List of entities. | | diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md deleted file mode 100644 index e775138da3..0000000000 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ /dev/null @@ -1,587 +0,0 @@ -# Ability - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The 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. - - -Manages the ability lifecycle and context. - - -## Modules to Import - - -``` -import Ability from '@ohos.application.Ability'; -``` - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| -| launchWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters for starting the ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| -| lastRequestWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters used when the ability was started last time.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| - - -## Ability.onCreate - -onCreate(want: Want, param: AbilityConstant.LaunchParam): void; - -Called to initialize the service logic when an ability is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this ability, including the ability name and bundle name.| - | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| - -**Example** - - ```js - class myAbility extends Ability { - onCreate(want, param) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## Ability.onWindowStageCreate - -onWindowStageCreate(windowStage: window.WindowStage): void - -Called when a **WindowStage** is created for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - } - } - ``` - - -## Ability.onWindowStageDestroy - -onWindowStageDestroy(): void - -Called when the **WindowStage** is destroyed for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageDestroy() { - console.log('onWindowStageDestroy'); - } - } - ``` - - -## Ability.onWindowStageRestore - -onWindowStageRestore(windowStage: window.WindowStage): void - -Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageRestore(windowStage) { - console.log('onWindowStageRestore'); - } - } - ``` - - -## Ability.onDestroy - -onDestroy(): void; - -Called when this ability is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## Ability.onForeground - -onForeground(): void; - -Called when this ability is running in the foreground. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onForeground() { - console.log('onForeground'); - } - } - ``` - - -## Ability.onBackground - -onBackground(): void; - -Callback when this ability is switched to the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onBackground() { - console.log('onBackground'); - } - } - ``` - - -## Ability.onContinue - -onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; - -Called to save data during the ability migration preparation process. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| - -**Example** - - ```js - class myAbility extends Ability { - onContinue(wantParams) { - console.log('onContinue'); - wantParams["myData"] = "my1234567"; - return true; - } - } - ``` - - -## Ability.onNewWant - -onNewWant(want: Want): void; - -Called when the ability startup mode is set to singleton. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Want parameters, such as the ability name and bundle name.| - -**Example** - - ```js - class myAbility extends Ability { - onNewWant(want) { - console.log('onNewWant, want:' + want.abilityName); - } - } - ``` - - -## Ability.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](#section188911144124715) | Yes| New configuration.| - -**Example** - - ```js - class myAbility extends Ability { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - - -## Caller - -Implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). - - -## Caller.call - -call(method: string, data: rpc.Sequenceable): Promise<void>; - -Sends sequenceable data to the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ // Custom sequenceable data structure - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); // See the definition of Sequenceable. - caller.call(method, msg) - .then(() => { - console.log('Caller call() called'); - }).catch((e) => { - console.log('Caller call() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - - } - ``` - - -## Caller.callWithResult - -callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; - -Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ - constructor(name, str) { - this.name = name; - this.str = str; - } - constructor() {} - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); - caller.callWithResult(method, msg) - .then((data) => { - console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); - data.readSequenceable(retmsg); - }).catch((e) => { - console.log('Caller callWithResult() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Caller.release - -release(): void; - -Releases the caller interface of the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.release(); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Caller.onRelease - -onRelease(callback: OnReleaseCallBack): void; - -Registers a callback that is invoked when the Stub on the target ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); - }); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Callee - -Implements callbacks for caller notification registration and unregistration. - - -## Callee.on - -on(method: string, callback: CaleeCallBack): void; - -Registers a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities.| - | callback | CaleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - function funcCallBack(pdata) { - console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble(0, ""); - pdata.readSequenceable(msg); - return new MyMessageAble(10, "Callee test"); - } - export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.on(method, funcCallBack); - } - } - ``` - - -## Callee.off - -off(method: string): void; - -Unregisters a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var method = 'call_Function'; - export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.off(method); - } - } - ``` - -## OnReleaseCallBack - -(msg: string): void; - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (msg: string) | function | Yes| No| Prototype of the listener function interface registered by the caller.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | - - - ## CaleeCallBack - -(indata: rpc.MessageParcel): rpc.Sequenceable; - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the message listener function interface registered by the callee.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md deleted file mode 100644 index 4e00922ba0..0000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ /dev/null @@ -1,56 +0,0 @@ -# AbilityConstant - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 9. - - -Provides parameters related to ability launch. - - -## Modules to Import - - -```js -import AbilityConstant from '@ohos.application.AbilityConstant'; -``` - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - -## AbilityConstant.LaunchReason - -Enumerates ability launch reasons. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| START_ABILITY | 1 | Ability startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| CALL | 2 | Call.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| CONTINUATION | 3 | Ability continuation.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityConstant.LaunchReason - -Enumerates reasons for the last exit. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| NORMAL | 2 | Normal status.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityConstant.OnContinueResult - -Enumerates ability continuation results. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| AGREE | 0 | Continuation agreed.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| REJECT | 1 | Continuation denied.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| MISMATCH | 2 | Mismatch.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md new file mode 100644 index 0000000000..0c8f62fcfb --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md @@ -0,0 +1,239 @@ +# AbilityDelegator + +> **Note** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityDelegator + +### startAbility + +startAbility(want: Want, callback: AsyncCallback\): void + +Starts an ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------ | +| want | [Want](js-apis-featureAbility.md#Want) | Yes | **Want** parameter for starting the ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +var abilityDelegator; +var want = { + bundleName: "bundleName", + abilityName: "abilityName" +}; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.startAbility(want, (err, data) => { + console.info("startAbility callback"); +}); +``` + + + +### startAbility + +startAbility(want: Want): Promise\ + +Starts an ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | --------------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes | **Want** parameter for starting the ability.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; +var want = { + bundleName: "bundleName", + abilityName: "abilityName" +}; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.startAbility(want).then((data: any) => { + console.info("startAbility promise"); +}); +``` + +### print + +print(msg: string, callback: AsyncCallback\): void + +Prints log information to the unit test console. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------ | +| msg | string | Yes | Log string. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +var abilityDelegator; +var msg = "msg"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.print(msg, (err) => { + console.info("print callback"); +}); +``` + + + +### print + +print(msg: string): Promise\ + +Prints log information to the unit test console. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| msg | string | Yes | Log string.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; +var msg = "msg"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.print(msg).then(() => { + console.info("print promise"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, callback: AsyncCallback\): void + +Executes a shell command. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| cmd | string | Yes | Shell command string. | +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, (err, data) => { + console.info("executeShellCommand callback"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void + +Executes a shell command with the timeout period specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ----------------------------- | +| cmd | string | Yes | Shell command string. | +| timeoutSecs | number | Yes | Command timeout period, in seconds.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object. | + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; +var timeout = 100; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, timeout, (err, data) => { + console.info("executeShellCommand callback"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, timeoutSecs: number): Promise\ + +Executes a shell command with the timeout period specified. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------------- | +| cmd | string | Yes | Shell command string. | +| timeoutSecs | number | No | Command timeout period, in seconds.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| Promise\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; +var timeout = 100; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { + console.info("executeShellCommand promise"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md new file mode 100644 index 0000000000..36a133137f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @@ -0,0 +1,24 @@ +# AbilityDelegatorArgs + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityDelegatorArgs + +Describes the test parameters. + +| Name | Type | Readable| Writable| Description | +| ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Yes | Bundle name of the application to test.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| testCaseNames | string | Yes | Yes | Test case names.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| testRunnerClassName | string | Yes | Yes | Names of the test executors that execute the test cases.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilitystage.md deleted file mode 100644 index 4f04fa0a10..0000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ /dev/null @@ -1,99 +0,0 @@ -# AbilityStage - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Runtime class for HAP files. It provides APIs to notify you when a HAP file starts loading. You can then initialize the HAP file, for example, pre-load resources and create threads. - - -## Modules to Import - - -```js -import AbilityStage from '@ohos.application.AbilityStage'; -``` - -## AbilityStage.onCreate - -onCreate(): void - -Called when the application is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` - - -## AbilityStage.onAcceptWant - -onAcceptWant(want: Want): string; - -Called when a specified ability is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` - - -## AbilityStage.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the global configuration is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, language:' + config.language); - } - } - ``` -## AbilityStage.context - -Describes the configuration information about the context. - -| Name | Type | Description | -| ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-featureAbility.md) | Called when initialization is performed during ability startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md deleted file mode 100644 index eaf0b4ceca..0000000000 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ /dev/null @@ -1,80 +0,0 @@ -# Context - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Provides the context for running code, including **applicationInfo** and **resourceManager**. - - -## Usage - - -You must extend **AbilityContext** to implement this module. - - -## Attributes -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| resourceManager | ResourceManager | Yes| No| **ResourceManager** object.| -| applicationInfo | ApplicationInfo | Yes| No| Information about the application.| -| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.| -| tempDir | string | Yes| No| Temporary file directory of the application.| -| filesDir | string | Yes| No| File directory of the application on the internal storage.| -| databaseDir | string | Yes| No| Storage directory of local data.| -| storageDir | string | Yes| No| Storage directory of lightweight data.| -| bundleCodeDir | string | Yes| No| Application installation path.| -| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| -| eventHub | [EventHub](js-apis-eventhub.md) | Yes| No| Event hub information.| - - -## Context.createBundleContext - -createBundleContext(bundleName: string): Context; - -Creates an application context. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context of the application created.| - -**Example** - - ```js - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - ``` - - -## Context.getApplicationContext - -getApplicationContext(): Context; - -Obtains the context of this application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context obtained.| - -**Example** - - ```js - // This part is mandatory. - let context = this.context.getApplicationContext(); - ``` diff --git a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md new file mode 100644 index 0000000000..6a956dad3e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md @@ -0,0 +1,22 @@ +# ShellCmdResult + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## ShellCmdResult + +Describes the shell command execution result. + +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| stdResult | string | Yes | Yes | Standard output content.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| exitCode | number | Yes | Yes | Result code.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index a803daded9..04e994eb64 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -1,7 +1,7 @@ # appManager > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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. Implements application management. @@ -9,7 +9,7 @@ Implements application management. ## Modules to Import - + ```js import app from '@ohos.application.appManager'; ``` @@ -77,18 +77,16 @@ Checks whether this application is running in a RAM constrained device. This API | Type| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return whether the the application is running in a RAM constrained device. If the the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | Promise<boolean> | Promise used to return whether the application is running in a RAM constrained device. If the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js - IsRamConstrainedDevicePromise(){ app.isRamConstrainedDevicePromise().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); - } ``` ## appManager.isRamConstrainedDevice @@ -103,17 +101,15 @@ Checks whether this application is running in a RAM constrained device. This API | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the the application is running in a RAM constrained device. If the the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running in a RAM constrained device. If the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js - IsRamConstrainedDeviceCallBack(){ app.isRamConstrainedDevicePromise((err, data) => { console.log('startAbility result failed:' + JSON.stringify(err)); console.log('startAbility result success:' + JSON.stringify(data)); }) - } ``` ## appManager.getAppMemorySize @@ -133,13 +129,11 @@ Obtains the memory size of this application. This API uses a promise to return t **Example** ```js - GetAppMemorySize(){ app.getAppMemorySize().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); - } ``` ## appManager.getAppMemorySize @@ -159,10 +153,65 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Example** ```js - GetAppMemorySizeCallBack(){ app.getAppMemorySize((err, data) => { console.log('startAbility result failed :' + JSON.stringify(err)); console.log('startAbility result success:' + JSON.stringify(data)); }) - } ``` +## appManager.getProcessRunningInfos8+ + +getProcessRunningInfos(): Promise>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise> | Promise used to return the process information.| + +**Example** + + ```js + app.GetProcessRunningInfos().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInfos8+ + +getProcessRunningInfos(callback: AsyncCallback>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback> | No| Callback used to return the process information.| + +**Example** + + ```js + app.GetProcessRunningInfos((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## ProcessRunningInfo + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| pid8+ | Read only | number | No | Process ID. | +| uid8+ | Read only | number | No | User ID.| +| processName8+ | Read only | string | No | Process name.| +| bundleNames8+ | Read only | Array\ | No | **bundleName** array in the running process.| diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index e3ba42ce09..691dea9eae 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -264,6 +264,7 @@ arrayList.removeByRange(2, 6); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void @@ -301,6 +302,7 @@ arrayList.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void @@ -335,6 +337,7 @@ arrayList.forEach((value, index) => { ``` ### sort + sort(comparator?: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -366,6 +369,7 @@ arrayList.sort(); ``` ### subArrayList + subArrayList(fromIndex: number, toIndex: number): ArrayList<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **ArrayList** instance. @@ -397,6 +401,7 @@ let result3 = arrayList.subArrayList(2, 6); ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -413,6 +418,7 @@ arrayList.clear(); ``` ### clone + clone(): ArrayList<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. @@ -436,6 +442,7 @@ let result = arrayList.clone(); ``` ### getCapacity + getCapacity(): number Obtains the capacity of this container. @@ -458,6 +465,7 @@ let result = arrayList.getCapacity(); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -480,6 +488,7 @@ let result = arrayList.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -502,6 +511,7 @@ let result = arrayList.isEmpty(); ``` ### increaseCapacityTo + increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. @@ -525,6 +535,7 @@ arrayList.increaseCapacityTo(8); ``` ### trimToCurrentLength + trimToCurrentLength(): void Trims the capacity of this container to its current length. diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 7787a55116..da5d93ba2a 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -22,15 +22,15 @@ The default duration of delayed suspension is 180000 when the battery level is h **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ---------------------------------------- | -| reason | string | Yes | Reason for delayed transition to the suspended state. | -| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | ------------------------------ | +| reason | string | Yes | Reason for delayed transition to the suspended state. | +| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| **Return value** -| Type | Description | -| ------------------------------------- | --------------------------------------- | -| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay. | +| Type | Description | +| ------------------------------------- | --------- | +| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| **Example** ```js @@ -50,10 +50,10 @@ Obtains the remaining duration before the application is suspended. This API use **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | --------------------------- | --------- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds. | +| Name | Type | Mandatory | Description | +| --------- | --------------------------- | ---- | ---------------------------------------- | +| requestId | number | Yes | ID of the suspension delay request. | +| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.| **Example** @@ -78,14 +78,14 @@ Obtains the remaining duration before the application is suspended. This API use **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ----------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| requestId | number | Yes | ID of the suspension delay request.| **Return value** -| Type | Description | +| Type | Description | | --------------------- | ---------------------------------------- | -| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds. | +| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| **Example** ```js @@ -107,9 +107,9 @@ Cancels the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ----------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| requestId | number | Yes | ID of the suspension delay request.| **Example** ```js @@ -128,12 +128,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | --------- | ---------------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ------------------------ | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -180,15 +180,15 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | --------- | ---------------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page when a continuous task notification is clicked. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** -| Type | Description | -| -------------- | ---------------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result. | **Example** @@ -229,10 +229,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------- | --------- | ----------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -260,13 +260,13 @@ Requests to cancel a continuous task. This API uses a promise to return the resu **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------- | --------- | -------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | +| Name | Type | Mandatory | Description | +| ------- | ----------------------------- | ---- | --------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | **Return value** -| Type | Description | -| -------------- | ---------------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result. | **Example** @@ -288,24 +288,24 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask -| Name | Type | Mandatory | Description | -| --------------- | ------ | --------- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level. | +| Name | Type | Mandatory | Description | +| --------------- | ------ | ---- | ---------------------------------------- | +| requestId | number | Yes | ID of the suspension delay request. | +| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| ## BackgroundMode8+ **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Value | Description | -| ----------------------- | ----- | -------------------------------- | -| DATA_TRANSFER | 1 | Data transfer. | -| AUDIO_PLAYBACK | 2 | Audio playback. | -| AUDIO_RECORDING | 3 | Audio recording. | -| LOCATION | 4 | Positioning and navigation. | -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related (reserved). | -| VOIP | 8 | Voice and video call (reserved). | -| TASK_KEEPING | 9 | Computing task. | +| Name | Value| Description | +| ----------------------- | ------ | ---------------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related (reserved). | +| VOIP | 8 | Voice and video call (reserved). | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices).| diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index f74e565b2d..947a272383 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. +> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. ## Modules to Import @@ -216,9 +216,9 @@ Obtains the connection status of a profile. **Return value** -| Type | Description | -| ---------------------------------------- | ------------- | -| [ProfileConnectionState](#ProfileConnectionState) | Profile connection state obtained.| +| Type | Description | +| ------------------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained.| **Example** @@ -1235,14 +1235,14 @@ Obtains the connection status of the profile. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device.| +| device | string | Yes | Address of the target device.| | **Return value** -| | | -| ---------------------------------------- | --------------- | -| Type | Description | +| | | +| ------------------------------------------------- | ----------------------- | +| Type | Description | | [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. | @@ -1904,7 +1904,7 @@ Subscribes to the characteristic write request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.| -| callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | +| callback | Callback<[CharacteristicWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | **Return value** @@ -1984,7 +1984,7 @@ Subscribes to the descriptor read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| -| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | +| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request from the GATT client. | **Return value** @@ -3116,10 +3116,10 @@ Defines the parameters of **BLEConnectChangedState**. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Type | Readable | Writable | Description | -| -------- | ---------------------------------------- | ---- | ---- | -------------------------------- | -| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| -| state | [ProfileConnectionState](#profileconnectionState) | Yes | Yes | BLE connection state. | +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | Yes | BLE connection state. | ## ProfileConnectionState @@ -3285,10 +3285,10 @@ Defines the profile state change parameters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Type | Readable | Writable | Description | -| -------- | ---------------------------------------- | ---- | ---- | ------------------- | -| deviceId | string | Yes | No | Address of a Bluetooth device. | -| state | [ProfileConnectionState](#ProfileConnectionState) | Yes | No | Profile connection state of the device.| +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | ------------------------------- | +| deviceId | string | Yes | No | Address of a Bluetooth device. | +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | No | Profile connection state of the device.| ## DeviceClass8+
diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index a87d894778..8f93a1e5d0 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,6 +1,6 @@ # CommonEvent -> **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -9,62 +9,63 @@ | ------------ | ------------------ | ---------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | N/A | -| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | N/A | -| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | N/A | -| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | N/A | -| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | N/A | -| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | N/A | -| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | N/A | -| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | N/A | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | N/A | -| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | N/A | -| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | N/A | -| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | N/A | -| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | N/A | -| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | N/A | -| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | N/A | -| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | N/A | -| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | N/A | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | N/A | -| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | N/A | -| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | N/A | -| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | N/A | -| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | N/A | -| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | N/A | -| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | N/A | -| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | N/A | -| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | N/A | -| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | N/A | -| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | N/A | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | N/A | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | N/A | -| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | N/A | -| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | N/A | -| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | N/A | -| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | N/A | -| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | N/A | -| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | N/A | -| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | N/A | -| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | N/A | -| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | N/A | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | | COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | N/A | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | | COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | N/A | -| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | N/A | -| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | N/A | -| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | N/A | -| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | N/A | -| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | N/A | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | +| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | +| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | +| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | +| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | | COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | | COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | N/A | -| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | N/A | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | | COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | | COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO | | COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | @@ -82,26 +83,26 @@ | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | N/A | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | N/A | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | | COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | N/A | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | | COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | @@ -111,34 +112,34 @@ | COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | N/A | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | | COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | | COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | -| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | N/A | -| COMMON_EVENT_CHARGING | usual.event.CHARGING | N/A | -| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | N/A | -| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | N/A | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | | COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | | COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | | COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | -| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | N/A | -| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | N/A | -| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | N/A | -| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | N/A | -| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | N/A | -| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | N/A | -| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | N/A | -| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | N/A | -| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | N/A | -| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | N/A | -| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | N/A | -| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | N/A | -| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | N/A | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | N/A | -| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | N/A | -| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | N/A | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | | COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| | COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| | COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| @@ -153,7 +154,7 @@ | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | N/A | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | | COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | ## Modules to Import @@ -174,8 +175,8 @@ Publishes a common event. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | -------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result.| +| event | Read only | string | Yes | Name of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -207,9 +208,9 @@ Publishes a common event with given attributes. This API uses a callback to retu | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| options | Read-only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -249,9 +250,9 @@ Publishes a common event to a specific user. This API uses a callback to return | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | -------------------- | ---- | ---------------------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| userId | Read-only | number | Yes | User ID.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| userId | Read only | number | Yes | User ID.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -286,10 +287,10 @@ Publishes a common event with given attributes to a specific user. This API uses | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| userId | Read-only| number | Yes| User ID.| -| options | Read-only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| userId | Read only| number | Yes| User ID.| +| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -331,8 +332,8 @@ Creates a subscriber. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ------------- | -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | Read-only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | -| callback | Read-only | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| +| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | Read only | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| **Example** @@ -340,12 +341,12 @@ 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. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); @@ -373,7 +374,7 @@ Creates a subscriber. This API uses a promise to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ------------- | -------- | ----------------------------------------------------- | ---- | -------------- | -| subscribeInfo | Read-only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| +| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| **Return value** | Type | Description | @@ -385,7 +386,7 @@ Creates a subscriber. This API uses a promise to return the result. ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; @@ -413,20 +414,20 @@ Subscribes to common events. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ---------- | -------- | --------------------------------------------------- | ---- | -------------------------------- | -| subscriber | Read-only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | Read-only | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| +| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | Read only | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| **Example** ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for common event subscription +// Callback for common event subscription. function SubscribeCallBack(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); @@ -435,7 +436,7 @@ function SubscribeCallBack(err, data) { } } -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); @@ -451,7 +452,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); ``` - + ## CommonEvent.unsubscribe @@ -463,22 +464,22 @@ Unsubscribes from common events. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | --------------------- | ---- | ------------------------ | -| subscriber | Read-only | CommonEventSubscriber | Yes | Subscriber object. | -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Readable/Writable| Type | Mandatory| Description | +| ---------- | -------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | Read only | AsyncCallback\ | No | Callback used to return the result.| **Example** ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for common event subscription +// Callback for common event subscription. function SubscribeCallBack(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); @@ -487,7 +488,7 @@ function SubscribeCallBack(err, data) { } } -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); @@ -499,7 +500,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { } } -// Callback for common event unsubscription +// Callback for common event unsubscription. function UnsubscribeCallBack(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); @@ -515,43 +516,6 @@ CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); ``` -## CommonEventPublishData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| --------------------- | -------- | -------------------- | ---- | ---------------------------- | -| bundleName | Read-only | string | No | Bundle name. | -| code | Read-only | number | No | Result code of the common event. | -| data | Read-only | string | No | Custom result data of the common event.| -| subscriberPermissions | Read-only | Array\ | No | Permissions required for subscribers to receive the common event. | -| isOrdered | Read-only | boolean | No | Whether the common event is an ordered one. | -| parameters | Read-only | {[key: string]: any} | No | Additional information about the common event. | - -## CommonEventSubscribeInfo - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | -| events | Read-only | Array\ | Yes | Common events to subscribe to. | -| publisherPermission | Read-only | string | No | Permission required for the publisher. | -| publisherDeviceId | Read-only | string | No | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Read-only | number | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Read-only | number | No | Subscriber priority. The value ranges from -100 to 1000. | - -## CommonEventData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------- | -| event | Read-only | string | Yes | Name of the common event to subscribe to. | -| bundleName | Read-only | string | No | Bundle name. | -| code | Read-only | number | No | Result code of the common event, which is used to transfer data of the int type. | -| data | Read-only | string | No | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Read-only | {[key: string]: any} | No | Additional information about the common event. | - ## CommonEventSubscriber ### getCode @@ -573,8 +537,7 @@ Obtains the result code of this common event. This API uses a callback to return ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event -getCode() { +// Callback for result code obtaining of an ordered common event. function getCodeCallback(err, Code) { if (err.code) { console.error("getCode failed " + JSON.stringify(err)); @@ -631,7 +594,7 @@ Sets the result code for this common event. This API uses a callback to return t ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result code setting of an ordered common event. function setCodeCallback(err) { if (err.code) { console.error("setCode failed " + JSON.stringify(err)); @@ -654,7 +617,13 @@ Sets the result code for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | Yes | Callback used to return the result code.| +| code | number | Yes | Result code of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result code.| **Example** @@ -680,14 +649,14 @@ Obtains the result data of this common event. This API uses a callback to return | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result data.| +| callback | AsyncCallback\ | Yes | Result data of the common event.| **Example** ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result data obtaining of an ordered common event. function getDataCallback(err, Data) { if (err.code) { console.error("getData failed " + JSON.stringify(err)); @@ -710,7 +679,7 @@ Obtains the result data of this common event. This API uses a promise to return | Type | Description | | ---------------- | ------------------ | -| Promise\ | Promise used to return the result data.| +| Promise\ | Result data of the common event.| **Example** @@ -767,7 +736,13 @@ Sets the result data for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| data | string | Yes | Callback used to return the result data.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result data.| **Example** @@ -802,7 +777,7 @@ Sets the result code and result data for this common event. This API uses a call ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result code and result data setting of an ordered common event. function setCodeDataCallback(err) { if (err.code) { console.error("setCodeAndData failed " + JSON.stringify(err)); @@ -826,7 +801,13 @@ Sets the result code and result data for this common event. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | code | number | Yes | Result code of the common event.| -| data | string | Yes | Callback used to return the result data.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -859,7 +840,7 @@ Checks whether this common event is an ordered one. This API uses a callback to ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for checking whether the current common event is an ordered one. function isOrderedCallback(err, isOrdered) { if (err.code) { console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); @@ -896,6 +877,62 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { }); ``` +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is a sticky one. This API uses a callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```js +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +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** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```js +var subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + ### abortCommonEvent abortCommonEvent(callback: AsyncCallback\): void @@ -915,7 +952,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for common event aborting. function abortCallback(err) { if (err.code) { console.error("abortCommonEvent failed " + JSON.stringify(err)); @@ -934,6 +971,12 @@ Aborts this common event. After the abort, the common event is not sent to the n **System capability**: SystemCapability.Notification.CommonEvent +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js @@ -965,7 +1008,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for clearing the aborted state of the current common event. function clearAbortCallback(err) { if (err.code) { console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); @@ -984,6 +1027,12 @@ Clears the aborted state of this common event. This API takes effect only for or **System capability**: SystemCapability.Notification.CommonEvent +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js @@ -1015,7 +1064,7 @@ Checks whether this common event is in the aborted state. This API takes effect ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for checking whether the current common event is in the aborted state. function getAbortCallback(err, AbortCommonEvent) { if (err.code) { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); @@ -1028,7 +1077,7 @@ subscriber.getAbortCommonEvent(getAbortCallback); ### getAbortCommonEvent -getAbortCommonEvent(): Promise\ +getAbortCommonEvent(): Promise\ Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1064,14 +1113,14 @@ Obtains the subscriber information. This API uses a callback to return the resul | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Promise used to return the subscriber information.| **Example** ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for subscriber information obtaining. function getSubscribeInfoCallback(err, SubscribeInfo) { if (err.code) { console.error("getSubscribeInfo failed " + JSON.stringify(err)); @@ -1107,3 +1156,42 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.error("getSubscribeInfo failed " + JSON.stringify(err)); }); ``` + +## CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------- | +| event | Read only | string | Yes | Name of the common event that is being received. | +| bundleName | Read only | string | No | Bundle name. | +| code | Read only | number | No | Result code of the common event, which is used to transfer data of the int type. | +| data | Read only | string | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | + + +## CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| --------------------- | -------- | -------------------- | ---- | ---------------------------- | +| bundleName | Read only | string | No | Bundle name. | +| code | Read only | number | No | Result code of the common event. | +| data | Read only | string | No | Custom result data of the common event.| +| subscriberPermissions | Read only | Array\ | No | Permissions required for subscribers to receive the common event. | +| isOrdered | Read only | boolean | No | Whether the common event is an ordered one. | +| isSticky | Read only | boolean | No | Whether the common event is a sticky one. | +| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | + +## CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | +| events | Read only | Array\ | Yes | Name of the common event to publish. | +| publisherPermission | Read only | string | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | Read only | string | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | Read only | number | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | Read only | number | No | Subscriber priority. The value ranges from -100 to 1000. | diff --git a/en/application-dev/reference/apis/js-apis-configuration.md b/en/application-dev/reference/apis/js-apis-configuration.md index 50803fb458..be8b93df49 100644 --- a/en/application-dev/reference/apis/js-apis-configuration.md +++ b/en/application-dev/reference/apis/js-apis-configuration.md @@ -9,7 +9,7 @@ Provides the configuration for the environment where the ability is running. ## Modules to Import - + ```js import Configuration from '@ohos.application.Configuration'; ``` @@ -19,10 +19,7 @@ import Configuration from '@ohos.application.Configuration'; **System capability**: SystemCapability.Ability.AbilityBase - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| Yes| Language of the application.| -| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction9+ | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| -| displayId9+ | number | Yes| No| ID of the display where the application is located.| +| language | string | Yes| Yes| Language of the application.| +| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| diff --git a/en/application-dev/reference/apis/js-apis-configurationconstant.md b/en/application-dev/reference/apis/js-apis-configurationconstant.md index 55f42b926d..541b665c73 100644 --- a/en/application-dev/reference/apis/js-apis-configurationconstant.md +++ b/en/application-dev/reference/apis/js-apis-configurationconstant.md @@ -9,7 +9,7 @@ Defines enumerated values of the configuration for the environment where the abi ## Modules to Import - + ```js import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; ``` @@ -27,50 +27,8 @@ ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| -| -------- | -------- | -------- | -| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| -| COLOR_MODE_DARK | 0 | Dark mode.| -| COLOR_MODE_LIGHT | 1 | Light mode.| - - -## ConfigurationConstant.Direction - -The value is obtained through the **ConfigurationConstant.Direction** API. - -**Example** - -``` -ConfigurationConstant.Direction.DIRECTION_VERTICAL -``` - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| -| -------- | -------- | -------- | -| DIRECTION_NOT_SET9+ | -1 | Unspecified direction.| -| DIRECTION_VERTICAL9+ | 0 | Vertical direction.| -| DIRECTION_HORIZONTAL9+ | 1 | Horizontal direction.| - - -## ConfigurationConstant.ScreenDensity - -The value is obtained through the **ConfigurationConstant.ScreenDensity** API. - -**Example** - -``` -ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_NOT_SET -``` - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET9+ | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI9+ | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI9+ | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI9+ | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI9+ | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI9+ | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI9+ | 640 | The screen resolution is xxxldpi.| +| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| +| COLOR_MODE_DARK | 0 | Dark mode.| +| COLOR_MODE_LIGHT | 1 | Light mode.| diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md new file mode 100644 index 0000000000..5e76a59477 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -0,0 +1,223 @@ +# Active Tag + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE**
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import connectedTag from '@ohos.connectedTag'; +``` + + +## connectedTag.init + +init(): boolean + +Initializes the active tag chip. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| + + +## connectedTag.uninit + +uninit(): boolean + +Uninitializes the active tag resources. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## connectedTag.readNdefTag + +readNdefTag(): Promise<string> + +Reads the content of this active tag. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<string> | Promise used to return the content of the active tag.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.readNdefTag().then(result => { + console.log("promise recv ndef response: " + result); + }); + ``` + +## connectedTag.readNdefTag + +readNdefTag(callback: AsyncCallback<string>): void + +Reads the content of this active tag. This method uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.readNdefTag(result => { + console.log("callback recv ndef response: " + result); + }); + ``` + +## connectedTag.writeNdefTag + +writeNdefTag(data: string): Promise<void> + +Writes data to this active tag. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result. This method returns no value.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + writeNdefTag.write("010203") + .then((value) => { + // Data is written to the tag. + console.log(`success to write event: ${value}`); + }).catch((err) => { + // Failed to write data to the tag. + console.error(`failed to write event because ${err.code}`); + }); + ``` + +## connectedTag.writeNdefTag + +writeNdefTag(data: string, callback: AsyncCallback<string>): void + +Writes data to this active tag. This method uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | data | string | Yes| Data to write. The maximum length is 1024 bytes.| + | callback | AsyncCallback<string> | Yes| Callback invoked to return the operation result.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.writeNdefTag("010203", (err, value) => { + if (err) { + // Failed to write data to the tag. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Data is written to the tag. + console.log(`success to write event: ${value}`); + }); + ``` + +## connectedTag.on('notify') + +on(type: "notify", callback: Callback<number>): void + +Registers the NFC field strength state events. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **notify**.| + | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| + +- Enumerates the field strength states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Field off. | + | 1 | Field on. | + + +## connectedTag.off('notify') + +off(type: "notify", callback?: Callback<number>): void + +Unregisters the NFC field strength state events. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **notify**.| + | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + var NFC_RF_NOTIFY = "notify"; + + var recvNfcRfNotifyFunc = result => { + console.info("nfc rf receive state: " + result); + } + + // Register event + connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); + + // Unregister event + connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); + ``` + +## NfcRfType + +Enumerates the NFC states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| NFC_RF_LEAVE | 0 | Field off. | +| NFC_RF_ENTER | 1 | Field on. | diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 78cc0b59d1..e4ffcaa90d 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -35,7 +35,7 @@ Converts an XML text into a JavaScript object. | Type| Description| | ------ | ---------------------------- | - | string | JavaScript object.| + | Object | JavaScript object.| - Example @@ -47,9 +47,13 @@ Converts an XML text into a JavaScript object. ' Work' + ' Play' + ''; - var conv = new convertxml.ConvertXML(); - var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false}); - console.log(result1) + let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} + let result = JSON.stringify(conv.convert(xml, options)); + console.log(result) ``` @@ -57,7 +61,7 @@ Converts an XML text into a JavaScript object. | Name| Type| Mandatory| Description| | ----------------- | -------- | ---- | ----------------------------------------------------------- | -| trim | boolean | No| Whether to trim the whitespace characters before and after the text. The default value is **false**.| +| trim | boolean | Yes| Whether to trim the whitespace characters before and after the text. The default value is **false**.| | ignoreDeclaration | boolean | No| Whether to ignore the XML declaration. The default value is **false**.| | ignoreInstruction | boolean | No| Whether to ignore the XML processing instruction. The default value is **false**.| | ignoreAttributes | boolean | No| Whether to print attributes across multiple lines and indent attributes. The default value is **false**.| @@ -65,14 +69,14 @@ Converts an XML text into a JavaScript object. | ignoreCDATA | boolean | No| Whether to ignore the element's CDATA information. The default value is **false**.| | ignoreDoctype | boolean | No| Whether to ignore the element's Doctype information. The default value is **false**.| | ignoreText | boolean | No| Whether to ignore the element's text information. The default value is **false**.| -| declarationKey | string | No| Name of the attribute key for **declaration** in the output object. The default value is **_declaration**.| -| instructionKey | string | No| Name of the attribute key for **instruction** in the output object. The default value is **_instruction**.| -| attributesKey | string | No| Name of the attribute key for **attributes** in the output object. The default value is **_attributes**.| -| textKey | string | No| Name of the attribute key for **text** in the output object. The default value is **_text**.| -| cdataKey | string | No| Name of the attribute key for **CDATA** in the output object. The default value is **_cdata**.| -| doctypeKey | string | No| Name of the attribute key for **Doctype** in the output object. The default value is **_doctype**.| -| commentKey | string | No| Name of the attribute key for **comment** in the output object. The default value is **_comment**.| -| parentKey | string | No| Name of the attribute key for **parent** in the output object. The default value is **_parent**.| -| typeKey | string | No| Name of the attribute key for **type** in the output object. The default value is **_type**.| -| nameKey | string | No| Name of the attribute key for **name** in the output object. The default value is **_name**.| -| elementsKey | string | No| Name of the attribute key for **elements** in the output object. The default value is **_elements**.| +| declarationKey | string | Yes| Name of the attribute key for **declaration** in the output object. The default value is **_declaration**.| +| instructionKey | string | Yes| Name of the attribute key for **instruction** in the output object. The default value is **_instruction**.| +| attributesKey | string | Yes| Name of the attribute key for **attributes** in the output object. The default value is **_attributes**.| +| textKey | string | Yes| Name of the attribute key for **text** in the output object. The default value is **_text**.| +| cdataKey | string | Yes| Name of the attribute key for **CDATA** in the output object. The default value is **_cdata**.| +| doctypeKey | string | Yes| Name of the attribute key for **Doctype** in the output object. The default value is **_doctype**.| +| commentKey | string | Yes| Name of the attribute key for **comment** in the output object. The default value is **_comment**.| +| parentKey | string | Yes| Name of the attribute key for **parent** in the output object. The default value is **_parent**.| +| typeKey | string | Yes| Name of the attribute key for **type** in the output object. The default value is **_type**.| +| nameKey | string | Yes| Name of the attribute key for **name** in the output object. The default value is **_name**.| +| elementsKey | string | Yes| Name of the attribute key for **elements** in the output object. The default value is **_elements**.| diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 4045752d3f..2f4b695a6c 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,1697 +1,813 @@ -# DataAbilityPredicates +# DataAbilityPredicates ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import + +## Modules to Import ``` import dataAbility from '@ohos.data.dataAbility' ``` -## System Capabilities -SystemCapability.DistributedDataManager.DataShare.Core - - -## dataAbility.createRdbPredicates - -createRdbPredicates\(name: string, dataAbilityPredicates: DataAbilityPredicates\): rdb.RdbPredicates - -Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

name

-

string

-

Yes

-

Table name in the RDB store.

-

dataAbilityPredicates

-

DataAbilityPredicates

-

Yes

-

DataAbilityPredicates object.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

rdb.RdbPredicates

-

RdbPredicates object created.

-
- -- Example - - ``` - let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() - dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) - let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) - ``` - - -## DataAbilityPredicates + + +## dataAbility.createRdbPredicates + + +createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates + + +Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Table name in the RDB store.| + | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object.| + +- Return value + | Type| Description| + | -------- | -------- | + | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| + +- Example: + ``` + let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() + dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) + let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) + ``` + + +## DataAbilityPredicates Provides predicates for implementing diverse query methods. -### equalTo - -equalTo\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value equal to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with a left parenthesis.

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

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with a right parenthesis.

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

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with the OR condition.

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

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates with the AND condition.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

low

-

ValueType

-

Yes

-

Minimum value to match the DataAbilityPredicates.

-

high

-

ValueType

-

Yes

-

Maximum value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

low

-

ValueType

-

Yes

-

Minimum value to match the DataAbilityPredicates.

-

high

-

ValueType

-

Yes

-

Maximum value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

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

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

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

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

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that can filter out duplicate records.

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

Name

-

Type

-

Mandatory

-

Description

-

value

-

number

-

Yes

-

Maximum number of records in a column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

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

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

Name

-

Type

-

Mandatory

-

Description

-

rowOffset

-

number

-

Yes

-

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

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

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

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

Name

-

Type

-

Mandatory

-

Description

-

fields

-

Array<string>

-

Yes

-

Names of columns grouped for querying data.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that groups rows that have the same value.

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

Name

-

Type

-

Mandatory

-

Description

-

indexName

-

string

-

Yes

-

Name of the index column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityRdbPredicates object that specifies the index column.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

Array<ValueType>

-

Yes

-

Array of ValueType to match.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

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

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

Array<ValueType>

-

Yes

-

Array of ValueType to match.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notIn("NAME", ["Lisa", "Rose"]) - ``` +### equalTo + + +equalTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + + +notEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + + +beginWrap(): DataAbilityPredicates + + +Adds a left parenthesis to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| + +- Example: + ``` + let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + + +endWrap(): DataAbilityPredicates + + +Adds a right parenthesis to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + + +or(): DataAbilityPredicates + + +Adds the OR condition to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + + +and(): DataAbilityPredicates + + +Adds the AND condition to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + + +contains(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + + +beginsWith(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + + +endsWith(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + + +isNull(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + + +isNotNull(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + + +like(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + + +glob(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + + +between(field: string, low: ValueType, high: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + + +notBetween(field: string, low: ValueType, high: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + + +greaterThan(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + + +lessThan(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + + +greaterThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + + +lessThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + + +orderByAsc(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + + +orderByDesc(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + + +distinct(): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let promiseDistinct = rdbStore.query(predicates, ["NAME"]) + promiseDistinct.then((resultSet) => { + console.log("distinct") + }).catch((err) => { + expect(null).assertFail(); + }) + ``` + + +### limitAs + + +limitAs(value: number): DataAbilityPredicates + + +Set a **DataAbilityPredicates** object to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | value | number | Yes| Maximum number of records.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + + +offsetAs(rowOffset: number): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + + +groupBy(fields: Array<string>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | fields | Array<string> | Yes| Names of columns to group.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + +### indexedBy + + +indexedBy(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to specify the index column. + + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | indexName | string | Yes| Name of the index column.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + + +in(field: string, value: Array<ValueType>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type Array and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](js-apis-data-rdb.md#valuetype)> | Yes| Array of **ValueType**s to match.| + + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + + +notIn(field: string, value: Array<ValueType>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type Array and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](js-apis-data-rdb.md#valuetype)> | Yes| Array of **ValueType**s to match.| + + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index f30b388e0f..ed0829f6f6 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,4 +1,4 @@ -# Distributed Object +# Distributed Data Object > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,16 +17,21 @@ import distributedObject from '@ohos.data.distributedDataObject' createDistributedObject(source: object): DistributedObject -Creates a **distributedObject** instance. You can specify the attribute of the instance in **source**. This method returns the **distributedObject** instance created. +Creates a distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | object | source | Yes| Attribute of the **distributedObject** instance to create.| + | source | object | Yes| Attribute of the distributed data object to create.| -- Example +**Return Value** + | Type| Description| + | -------- | -------- | + | [DistributedObject](#distributedobject) | Distributed data object created.| + +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' // Create a distributedObject instance. The attribute type of the object can be string, number, boolean, or Object. @@ -39,16 +44,16 @@ Creates a **distributedObject** instance. You can specify the attribute of the i genSessionId(): string -Creates a session ID randomly. +Creates a random session ID. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- Return value +**Return Value** | Type| Description| | -------- | -------- | | string | Session ID created.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var sessionId = distributedObject.genSessionId(); @@ -58,20 +63,29 @@ Creates a session ID randomly. ## DistributedObject Represents a **distributedObject** instance. + ### setSessionId setSessionId(sessionId?: string): boolean -Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. To remove a device from the distributed network, set this parameter to "" or leave it unspecified. If **true** is returned, the session ID is set successfully. +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** -- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed object on a trusted network.| + | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + +**Return Value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | -- Example +**Example** + ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -87,17 +101,17 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void -Subscribes to the data changes of this distributed object. +Subscribes to the data changes of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data change events.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the data changes of the distributed object. In the callback, **sessionId** indicates the session ID of the distributed object, and **fields** indicates the attributes of the object.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the attributes of the distributed data object changed.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -116,18 +130,18 @@ Subscribes to the data changes of this distributed object. off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void -Unsubscribes from the data changes of this distributed object. +Unsubscribes from the data changes of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data change events.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback used to return changes of the distributed object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| + | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data change events.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the attributes of the distributed data object changed.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -135,7 +149,7 @@ Unsubscribes from the data changes of this distributed object. g_object.on("change", function (sessionId, changeData) { console.info("change" + sessionId); }); - // Unsubscribe from the data change callback for the specified distributed object. + // Unsubscribe from the data change callback for the specified distributed data object. g_object.off("change", function (sessionId, changeData) { console.info("change" + sessionId); }); @@ -147,17 +161,19 @@ Unsubscribes from the data changes of this distributed object. on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void -Subscribes to the status changes (online or offline) of this distributed object. +Subscribes to the status changes (online or offline) of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is "status", which indicates the status (online or offline) change events.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status changes of the distributed object. In the callback, **sessionId** indicates the session ID of the distributed object, and **status** indicates the online or offline status of the distributed object.| + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the online or offline status.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the network ID of the device.
**status** indicates the status, which can be online or offline.| + + -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -172,24 +188,24 @@ Subscribes to the status changes (online or offline) of this distributed object. off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void -Unsubscribes from the status (online or offline) changes of the distributed object. +Unsubscribes from the status (online or offline) changes of the distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is "status", which indicates the status (online or offline) change events.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status changes. If this parameter is not specified, all the status change callbacks will be unregistered.| + | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status changes. If this parameter is not specified, all the status change callbacks will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' g_object.on("status", function (sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; }); - // Unsubscribe from the status change callback for the specified distributed object. + // Unsubscribe from the status change callback for the specified distributed data object. g_object.off("status", function (sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; }); diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 6d92a418fa..dbc00546fe 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,7 +1,6 @@ # Relational Database -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,71 +11,75 @@ import data_rdb from '@ohos.data.rdb' ``` -## System Capabilities -SystemCapability.DistributedDataManager.RelationalStore.Core - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void -Obtains a relational database (RDB) store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result. +Obtains a relational database (RDB) store. This method uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| - | version | number | Yes| RDB store version.| - | callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example - ``` - import Ability from '@ohos.application.Ability' - import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - const STORE_CONFIG = { name: "RdbTest.db"} - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { - rdbStore.executeSql(SQL_CREATE_TABLE) - console.info(TAG + 'create table done.') - }) - } - ``` +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| +| version | number | Yes| RDB store version.| +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| + +**Example** + +``` +import data_rdb from '@ohos.data.rdb' +const STORE_CONFIG = { name: "RdbTest.db"} +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info('create table done.') +}) +``` ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> -Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result. +Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| - | version | number | Yes| RDB store version.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| +**Parameters** -- Example - ``` - import Ability from '@ohos.application.Ability' - import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - const STORE_CONFIG = { name: "RdbTest.db" } - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); - promise.then(async (rdbStore) => { - await rdbStore.executeSql(SQL_CREATE_TABLE, null) - }).catch((err) => { - expect(null).assertFail(); - }) - } - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| +| version | number | Yes| RDB store version.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| + +**Example** + +``` +import data_rdb from '@ohos.data.rdb' +const STORE_CONFIG = { name: "RdbTest.db" } +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promisegetRdb = data_rdb.getRdbStore(STORE_CONFIG, 1); +promisegetRdb.then(async (rdbStore) => { + let promiseExecSql = rdbStore.executeSql(SQL_CREATE_TABLE, null) + promiseExecSql.then(() => { + console.info('executeSql creat done.') + }).catch((err) => { + console.log("executeSql creat err.") + }) +}).catch((err) => { + console.log("getRdbStore err.") +}) +``` ## data_rdb.deleteRdbStore @@ -84,21 +87,21 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g Deletes an RDB store. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | name | string | Yes| Name of the RDB store to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| name | string | Yes| Name of the RDB store to delete.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` - import Ability from '@ohos.application.Ability' import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { - console.info(TAG + 'delete store done.')}) - } + data_rdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { + console.info('delete store done.') + }) ``` ## data_rdb.deleteRdbStore @@ -107,27 +110,28 @@ deleteRdbStore(context: Context, name: string): Promise<void> Deletes an RDB store. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | name | string | Yes| Name of the RDB store to delete.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| name | string | Yes| Name of the RDB store to delete.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - import Ability from '@ohos.application.Ability' import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") - promise.then(()=>{ - console.info(TAG + 'delete store done.') - }) - } + let promisedeleteRdb = data_rdb.deleteRdbStore("RdbTest.db") + promisedeleteRdb.then(()=>{ + console.info('delete store done.') + }).catch((err) => { + console.log("deleteRdbStore err.") + }) ``` ## RdbPredicates @@ -142,55 +146,58 @@ constructor(name: string) A constructor used to create an **RdbPredicates** object. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Database table name.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database table name.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ``` -### inDevices +### inDevices8+ -inDevices(devices: Array): RdbPredicates; +inDevices(devices: Array<string>): RdbPredicates Specifies a remote device on the network during distributed database synchronization. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | devices | Array | Yes| ID of the remote device to specify.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| devices | Array<string> | Yes| ID of the remote device to specify.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicate.inDevices(['12345678abcde']) ``` -### inAllDevices +### inAllDevices8+ -inAllDevices(): RdbPredicates; +inAllDevices(): RdbPredicates Connects to all remote devices on the network during distributed database synchronization. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inAllDevices() @@ -203,19 +210,20 @@ equalTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -229,19 +237,20 @@ notEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notEqualTo("NAME", "lisi") @@ -255,13 +264,14 @@ beginWrap(): RdbPredicates Adds a left parenthesis to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -280,13 +290,14 @@ endWrap(): RdbPredicates Adds a right parenthesis to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -305,13 +316,14 @@ or(): RdbPredicates Adds the OR condition to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -327,13 +339,14 @@ and(): RdbPredicates Adds the AND condition to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -344,24 +357,24 @@ Adds the AND condition to the **RdbPredicates**. ### contains -contains(field: string, value: string): RdbPredicat - +contains(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string containing the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.contains("NAME", "os") @@ -375,19 +388,20 @@ beginsWith(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that starts with the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.beginsWith("NAME", "os") @@ -401,19 +415,20 @@ endsWith(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that ends with the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.endsWith("NAME", "se") @@ -427,16 +442,17 @@ isNull(field: string): RdbPredicates Sets the **RdbPredicates** to match the field whose value is null. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| - Example ``` @@ -452,18 +468,19 @@ isNotNull(field: string): RdbPredicates Sets the **RdbPredicates** to match the field whose value is not null. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNotNull("NAME") @@ -477,19 +494,20 @@ like(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that is similar to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.like("NAME", "%os%") @@ -503,19 +521,20 @@ glob(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match the specified string. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.
Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.glob("NAME", "?h*g") @@ -529,20 +548,21 @@ between(field: string, low: ValueType, high: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.between("AGE", 10, 50) @@ -556,20 +576,21 @@ notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notBetween("AGE", 10, 50) @@ -578,24 +599,24 @@ Sets the **RdbPredicates** to match the field with data type **ValueType** and v ### greaterThan -greaterThan(field: string, value: ValueType): RdbPredicatesgr - +greaterThan(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThan("AGE", 18) @@ -609,19 +630,20 @@ lessThan(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThan("AGE", 20) @@ -636,19 +658,20 @@ greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThanOrEqualTo("AGE", 18) @@ -663,19 +686,20 @@ lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThanOrEqualTo("AGE", 20) @@ -690,18 +714,19 @@ orderByAsc(field: string): RdbPredicates Sets the **RdbPredicates** to match the column with values sorted in ascending order. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByAsc("NAME") @@ -716,18 +741,19 @@ orderByDesc(field: string): RdbPredicates Sets the **RdbPredicates** to match the column with values sorted in descending order. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByDesc("AGE") @@ -741,17 +767,24 @@ distinct(): RdbPredicates Sets the **RdbPredicates** to filter out duplicate records. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct("NAME") - rdbStore.query(predicates, ["NAME"]) + let promisequery = rdbStore.query(predicates, ["NAME"]) + promisequery.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("query err.") + }) ``` @@ -762,18 +795,19 @@ limitAs(value: number): RdbPredicates Sets the **RdbPredicates** to specify the maximum number of records. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").limitAs(3) @@ -787,18 +821,19 @@ offsetAs(rowOffset: number): RdbPredicates Sets the **RdbPredicates** to specify the start position of the returned result. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").offsetAs(3) @@ -812,18 +847,19 @@ groupBy(fields: Array<string>): RdbPredicates Sets the **RdbPredicates** to group rows that have the same value into summary rows. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.groupBy(["AGE", "NAME"]) @@ -832,23 +868,24 @@ Sets the **RdbPredicates** to group rows that have the same value into summary r ### indexedBy -indexedBy(indexName: string): RdbPredicates - +indexedBy(field: string): RdbPredicates Sets the **RdbPredicates** object to specify the index column. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Name of the index column.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| +**Return value** -- Example +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.indexedBy("SALARY_INDEX") @@ -862,20 +899,21 @@ in(field: string, value: Array<ValueType>): RdbPredicates Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.in("AGE", [18, 20]) @@ -889,20 +927,21 @@ notIn(field: string, value: Array<ValueType>): RdbPredicates Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notIn("NAME", ["Lisa", "Rose"]) @@ -920,14 +959,16 @@ insert(name: string, values: ValuesBucket, callback: AsyncCallback<number> Inserts a row of data into a table. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the target table.| - | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** ``` const valueBucket = { "NAME": "Lisa", @@ -936,8 +977,8 @@ Inserts a row of data into a table. This method uses a callback to return the re "CODES": new Uint8Array([1, 2, 3, 4, 5]), } rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { - expect(1).assertEqual(ret) - console.log(TAG + "insert first done: " + ret)}) + console.log("insert first done: " + ret) + }) ``` @@ -947,18 +988,20 @@ insert(name: string, values: ValuesBucket):Promise<number> Inserts a row of data into a table. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the target table.| - | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** ``` const valueBucket = { "NAME": "Lisa", @@ -966,10 +1009,12 @@ Inserts a row of data into a table. This method uses a promise to return the res "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } - let promise = rdbStore.insert("EMPLOYEE", valueBucket) - promise.then(async (ret) => { - await console.log(TAG + "insert first done: " + ret) - }).catch((err) => {}) + let promiseinsert = rdbStore.insert("EMPLOYEE", valueBucket) + promiseinsert.then(async (ret) => { + console.log("insert first done: " + ret) + }).catch((err) => { + console.log("insert err.") + }) ``` @@ -979,14 +1024,16 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallba Updates data in the database based on the specified RdbPredicates object. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| + +**Example** ``` const valueBucket = { "NAME": "Rose", @@ -997,7 +1044,7 @@ Updates data in the database based on the specified RdbPredicates object. This m let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.update(valueBucket, predicates, function (err, ret) { - console.log(TAG + "updated row count: " + changedRows)}) + console.log("updated row count: " + changedRows)}) ``` @@ -1007,18 +1054,20 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> Updates data in the database based on the specified RdbPredicates object. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of rows updated.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| -- Example +**Example** ``` const valueBucket = { "NAME": "Rose", @@ -1028,10 +1077,12 @@ Updates data in the database based on the specified RdbPredicates object. This m } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") - let promise = rdbStore.update(valueBucket, predicates) - promise.then(async (ret) => { - await console.log(TAG + "updated row count: " + changedRows) - }).catch((err) => {}) + let promiseupdate = rdbStore.update(valueBucket, predicates) + promiseupdate.then(async (ret) => { + console.log("updated row count: " + changedRows) + }).catch((err) => { + console.log("update err.") + }) ``` @@ -1042,19 +1093,21 @@ delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void Deletes data from the database based on the specified RdbPredicates object. This method uses a callback to return the result. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows deleted.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.delete(predicates, function (err, rows) { - console.log(TAG + "delete rows: " + rows)}) + console.log("delete rows: " + rows) + }) ``` @@ -1064,24 +1117,28 @@ delete(rdbPredicates: RdbPredicates):Promise<number> Deletes data from the database based on the specified RdbPredicates object. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of rows deleted.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| -- Example +**Example** ``` - let predicates = new data_rdb.RdbPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") - let promise = rdbStore.delete(predicates) - promise.then((rows) => { - console.log(TAG + "delete rows: " + rows) - }).catch((err) => {}) + let predicatesdelete = new data_rdb.RdbPredicates("EMPLOYEE") + predicatesdelete.equalTo("NAME", "Lisa") + let promisedelete = rdbStore.delete(predicates) + promisedelete.then((rows) => { + console.log("delete rows: " + rows) + }).catch((err) => { + console.log("delete err.") + }) ``` @@ -1091,20 +1148,23 @@ query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: Asyn Queries data in the database based on specified conditions. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| - | columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| - | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }) ``` @@ -1114,25 +1174,30 @@ query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<Re Queries data in the database based on specified conditions. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| - | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") - let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - promise.then((resultSet) => { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + let promisequery = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequery.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("query err.") + }) ``` @@ -1142,18 +1207,21 @@ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback& Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| - | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }) ``` @@ -1163,23 +1231,28 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` - let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) - promise.then((resultSet) => { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + let promisequerySql = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) + promisequerySql.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("querySql err.") + }) ``` @@ -1189,17 +1262,20 @@ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallbac Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a callback to return the execution result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` rdbStore.executeSql("DELETE FROM EMPLOYEE", null, function () { - console.info(TAG + 'delete done.')}) + console.info('delete done.') + }) ``` @@ -1209,37 +1285,122 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a promise to return the execution result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - let promise = rdbStore.executeSql("DELETE FROM EMPLOYEE") - promise.then(() => { - console.info(TAG + 'delete done.')}) + let promiseexecuteSql = rdbStore.executeSql("DELETE FROM EMPLOYEE") + promiseexecuteSql.then(() => { + console.info('delete done.') + }).catch((err) => { + console.log("executeSql err.") + }) ``` -### setDistributedTables +### beginTransaction8+ + +beginTransaction():void + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() +``` + + +### commit8+ + +commit():void -setDistributedTables(tables: Array, callback: AsyncCallback): void; +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() +``` + + +### rollBack8+ + +rollBack():void; + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +``` + + +### setDistributedTables8+ + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void Sets a list of distributed tables. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | tables | Array | Yes| Names of the distributed tables to be set.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| tables | Array<string> | Yes| Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { @@ -1251,46 +1412,50 @@ Sets a list of distributed tables. This method uses a callback to return the res ``` -### setDistributedTables +### setDistributedTables8+ - setDistributedTables(tables: Array): Promise; + setDistributedTables(tables: Array<string>): Promise<void> Sets a list of distributed tables. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | tables | Array | Yes| Names of the distributed tables to be set.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| tables | Array<string> | Yes| Names of the distributed tables to set.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) - promise.then(() => { + let promiseset = rdbStore.setDistributedTables(["EMPLOYEE"]) + promiseset.then(() => { console.info("setDistributedTables success.") }).catch((err) => { - console.info("setDistributedTables failed."") + console.info("setDistributedTables failed.") }) ``` -### obtainDistributedTableName +### obtainDistributedTableName8+ -obtainDistributedTableName(device: string, table: string, callback: AsyncCallback): void; +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | device | string | Yes| Remote device.| - | table | string | Yes| Local table name.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Remote device.| +| table | string | Yes| Local table name.| +| callback | AsyncCallback<string> | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** ``` rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { @@ -1302,47 +1467,51 @@ Obtains the distributed table name for a remote device based on the local table ``` -### obtainDistributedTableName +### obtainDistributedTableName8+ - obtainDistributedTableName(device: string, table: string): Promise; + obtainDistributedTableName(device: string, table: string): Promise<string> Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | device | string | Yes| Remote device.| - | table | string | Yes| Local table name.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Remote device.| +| table | string | Yes| Local table name.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** ``` - let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") - promise.then((tableName) => { + let promiseDistr = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") + promiseDistr.then((tableName) => { console.info('obtainDistributedTableName success, tableName=' + tableName) }).catch((err) => { console.info('obtainDistributedTableName failed.') }) ``` -### sync +### sync8+ -sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void; +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void Synchronizes data between devices. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mode | SyncMode | Yes| Data synchronization mode, which can be **push** or **pull**.| - | predicates | RdbPredicates | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| - | callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| +| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** ``` let predicate = new rdb.RdbPredicates('EMPLOYEE') predicate.inDevices(['12345678abcde']) @@ -1359,77 +1528,89 @@ Synchronizes data between devices. This method uses a callback to return the res ``` -### sync +### sync8+ - sync(mode: SyncMode, predicates: RdbPredicates): Promise>; + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> Synchronizes data between devices. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mode | SyncMode | Yes| Data synchronization mode, which can be **push** or **pull**.| - | predicates | RdbPredicates | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**Return value** -- Example +| Type| Description| +| -------- | -------- | +| Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** ``` - let predicate = new rdb.RdbPredicates('EMPLOYEE') - predicate.inDevices(['12345678abcde']) - let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate) - promise.then(result) { + let predicatesync = new data_rdb.RdbPredicates('EMPLOYEE') + predicatesync.inDevices(['12345678abcde']) + let promisesync = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesync) + promisesync.then((result) =>{ console.log('sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } - }).catch((err) => { - console.log('sync failed') - }) + }).catch((err) => { + console.log('sync failed') + }) ``` -### on +### on('dataChange')8+ -on(event: 'dataChange', type: SubscribeType, observer: Callback>): void; +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | SubscribeType | Yes| Type defined in **SubscribeType**.| - | observer | Callback> | Yes| Observer that listens for the data changes in the RDB store.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| The value is'dataChange', which indicates a data change event.| +| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| + +**Example** ``` function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { console.log('device=' + device[i] + ' data changed') - } - } - try { - rdbStore.on('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) - } catch (err) { - console.log('register observer failed') - } + } + } + try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + } catch (err) { + console.log('register observer failed') + } ``` -### off +### off('dataChange')8+ -off(event:'dataChange', type: SubscribeType, observer: Callback>): void; +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void Deletes the specified observer of the RDB store. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | SubscribeType | Yes| Type defined in **SubscribeType**.| - | observer | Callback> | Yes| Data change observer registered.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| The value is'dataChange', which indicates a data change event.| +| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| observer | Callback<Array<string>> | Yes| Data change observer registered.| + +**Example** -- Example ``` function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { @@ -1437,7 +1618,7 @@ Deletes the specified observer of the RDB store. This method uses a callback to } } try { - rdbStore.off('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('unregister observer failed') } @@ -1448,6 +1629,8 @@ Deletes the specified observer of the RDB store. This method uses a callback to Manages the configuration of an RDB store. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | name | string | Yes| Database file name.| @@ -1457,6 +1640,8 @@ Manages the configuration of an RDB store. Defines the data types allowed. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + | Name| Description| | -------- | -------- | | number | Number.| @@ -1468,25 +1653,30 @@ Defines the data types allowed. Defines a bucket to store key-value pairs. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes| Defines a bucket to store key-value pairs.| -## SyncMode +## SyncMode8+ Defines the database synchronization mode. -| Name| Description| -| -------- | -------- | -| SYNC_MODE_PUSH | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | Data is loaded from a remote device to a local device.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Default Value| Description| +| -------- | ----- |----- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| -## SubscribeType +## SubscribeType8+ Defines the subscription type. -| Name| Description| -| -------- | -------- | -| SUBSCRIBE_TYPE_REMOTE | Subscribe to remote data changes.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Default Value| Description| +| -------- | ----- |---- | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 654cff58ad..e383a53035 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,15 +1,12 @@ -# Result Set +# Result Set ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## System Capabilities -SystemCapability.DistributedDataManager.RelationalStore.Core -## Usage +## Usage -The **resultSet** object is obtained by using [**RdbStore.query\(\)**](js-apis-data-rdb.md#query). +You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain the **resultSet** object. ``` import dataRdb from '@ohos.data.rdb'; @@ -17,779 +14,392 @@ let predicates = new dataRdb.RdbPredicates("EMPLOYEE") predicates.equalTo("AGE", 18) let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { - console.log("resultSet columnNames:" + resultSet.columnNames); - console.log("resultSet columnCount:" + resultSet.columnCount); + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) ``` -## ResultSet - -Provides methods to access the result set, which is obtained by querying the relational database \(RDB\) store. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnNames

-

Array<string>

-

Yes

-

Names of all columns in the result set.

-

columnCount

-

number

-

Yes

-

Number of columns in the result set.

-

rowCount

-

number

-

Yes

-

Number of rows in the result set.

-

rowIndex

-

number

-

Yes

-

Index of the current row in the result set.

-

isAtFirstRow

-

boolean

-

Yes

-

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

-

isAtLastRow

-

boolean

-

Yes

-

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

-

isEnded

-

boolean

-

Yes

-

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

-

isStarted

-

boolean

-

Yes

-

Whether the cursor has been moved.

-

isClosed

-

boolean

-

Yes

-

Whether the result set is closed.

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

Name

-

Type

-

Mandatory

-

Description

-

columnName

-

string

-

Yes

-

Name of the column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Index of the column.

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

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the column.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Name of the column.

-
- -- Example - - ``` - const id = resultSet.getColumnName(0) - const name = resultSet.getColumnName(1) - const age = resultSet.getColumnName(2) - ``` - - -### goTo - -goTo\(offset:number\): boolean + + + +## ResultSet + +Provides methods to access the result set, which is obtained by querying the relational database (RDB) store. + + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| columnNames | Array<string> | Yes| Names of all columns in the result set.| +| columnCount | number | Yes| Number of columns in the result set.| +| rowCount | number | Yes| Number of rows in the result set.| +| rowIndex | number | Yes| Index of the current row in the result set.| +| isAtFirstRow | boolean | Yes| Whether the cursor is in the first row of the result set.| +| isAtLastRow | boolean | Yes| Whether the cursor is in the last row of the result set.| +| isEnded | boolean | Yes| Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes| Whether the cursor has been moved.| +| isClosed | boolean | Yes| Whether the result set is closed.| + + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| + +- Example + ``` + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("ID")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### getColumnName + +getColumnName(columnIndex: number): string + +Obtains the column name based on the column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| + +- Return value + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| + +- Example + ``` + const id = resultSet.getColumnName(0) + const name = resultSet.getColumnName(1) + const age = resultSet.getColumnName(2) + ``` + + +### goTo + +goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

offset

-

number

-

Yes

-

Offset relative to the current position.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goTo(1); - resultSet.close(); - resultSet = null; - }) - ``` - - -### goToRow - -goToRow\(position: number\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoto.then((resultSet) { + resultSet.goTo(1) + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` + + +### goToRow + +goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

position

-

number

-

Yes

-

Position to which the cursor is to be moved.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToRow(1); - resultSet.close(); - resultSet = null - }) - ``` - - -### goToFirstRow - -goToFirstRow\(\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -Moves the cursor to the first row of the result set. +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Return values +- Example + ``` + let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygotorow.then((resultSet) { + resultSet.goToRow(5) + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
-- Example +### goToFirstRow - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToFirstRow(); - resultSet.close(); - resultSet = null; - }) - ``` +goToFirstRow(): boolean -### goToLastRow +Moves the cursor to the first row of the result set. -goToLastRow\(\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -Moves the cursor to the last row of the result set. +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Return values +- Example + ``` + let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoFirst.then((resultSet) { + resultSet.goToFirstRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
-- Example +### goToLastRow - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToLastRow(); - resultSet.close(); - resultSet = null; - }) - ``` +goToLastRow(): boolean +Moves the cursor to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoLast.then((resultSet) { + resultSet.goToLastRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` -### goToNextRow -goToNextRow\(\): boolean +### goToNextRow + +goToNextRow(): boolean Moves the cursor to the next row in the result set. -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoNext.then((resultSet) { resultSet.goToNextRow() resultSet.close() - resultSet = null; - }) - ``` + }).catch((err) => { + console.log('query failed') + }) + ``` -### goToPreviousRow +### goToPreviousRow -goToPreviousRow\(\): boolean +goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -- Return values +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
+- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToPreviousRow(); - resultSet.close(); - resultSet = null - }) - ``` +- Example + ``` + let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoPrev.then((resultSet) { + resultSet.goToPreviousRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` -### getBlob +### getBlob -getBlob\(columnIndex: number\): Uint8Array +getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

Uint8Array

-

Value in the specified column as a byte array.

-
- -- Example - - ``` - const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) - ``` - - -### getString - -getString\(columnIndex: number\): string +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| + +- Example + ``` + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + ``` + + +### getString + +getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Value in the specified column as a string.

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

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Value in the specified column as a Long.

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

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Value in the specified column as a double.

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

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

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

-
- -- Example - - ``` - const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) - ``` - - -### close - -close\(\): void - -Closes the result set. - -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.close(); - resultSet = null - }) - ``` +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| + +- Example + ``` + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + ``` + + +### getLong + +getLong(columnIndex: number): number + +Obtains the value in the specified column in the current row as a Long. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| + +- Example + ``` + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + ``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value in the specified column in the current row as a double. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| + +- Example + ``` + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column of the current row is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| + +- Example + ``` + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + ``` + + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Example + ``` + let predicatesclose = new dataRdb.RdbPredicates("EMPLOYEE") + let predicatesclose = rdbStore.query(predicatesclose, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoPrev.then((resultSet) { + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index 1f77fa1715..18cc1ce8d9 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -4,7 +4,8 @@ Lightweight storage provides applications with data processing capability and al > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -47,10 +48,16 @@ Reads a file and loads the data to the **Storage** instance in synchronous mode. import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - let storage = dataStorage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() + context.getFilesDir((err, path) => { + if (err) { + console.error('getFilesDir failed. err: ' + JSON.stringify(err)); + return; + } + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + let storage = dataStorage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() + }); ``` @@ -74,15 +81,21 @@ Reads a file and loads the data to the **Storage** instance. This method uses an import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - dataStorage.getStorage(path + '/mystore', function (err, storage) { + context.getFilesDir((err, path) => { if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') + console.error('getFilesDir failed. err: ' + JSON.stringify(err)); return; } - storage.putSync('startup', 'auto') - storage.flushSync() - }) + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + dataStorage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + storage.putSync('startup', 'auto') + storage.flushSync() + }) + }); ``` @@ -110,14 +123,20 @@ Reads a file and loads the data to the **Storage** instance. This method uses a import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - let promisegetSt = dataStorage.getStorage(path + '/mystore') - promisegetSt.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) + context.getFilesDir((err, path) => { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + let promisegetSt = dataStorage.getStorage(path + '/mystore') + promisegetSt.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Get the storage failed, path: " + path + '/mystore') + }) + }); ``` @@ -250,7 +269,7 @@ removeStorageFromCache(path: string): Promise<void> Removes the singleton **Storage** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -426,7 +445,7 @@ put(key: string, value: ValueType): Promise<void> Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush()** or **flushSync()**. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -522,7 +541,7 @@ has(key: string): Promise<boolean> Checks whether the storage object contains data with a given key. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -678,7 +697,7 @@ flush(): Promise<void> Saves the modification of this object to the **Storage** instance and synchronizes the modification to the file. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -747,7 +766,7 @@ clear(): Promise<void> Clears this **Storage** object. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index fb34371c00..10d3684392 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -1,5 +1,8 @@ # DataAbilityHelper Module (JavaScript SDK APIs) +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ``` diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index a8931d24e4..128dc378de 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -49,7 +49,7 @@ Inserts an entry at the front of this container. **Example** ``` -let deque = new Deque; +let deque = new Deque(); deque.insertFront("a"); deque.insertFront(1); let b = [1, 2, 3]; @@ -73,7 +73,7 @@ Inserts an entry at the end of this container. **Example** ``` -let deque = new Deque; +let deque = new Deque(); deque.insertEnd("a"); deque.insertEnd(1); let b = [1, 2, 3]; @@ -158,6 +158,7 @@ let result = deque.popLast(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void @@ -193,7 +194,7 @@ deque.forEach((value, index) => { ### getFirst -getFirst(): T; +getFirst(): T Obtains the first entry of this container. diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 43e248fb82..93ab553ef1 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,456 +1,213 @@ -# Device Management +# Device Management ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are system APIs and cannot be called by third-party applications. -## Modules to Import + +## Modules to import: ``` import deviceManager from '@ohos.distributedHardware.deviceManager'; ``` -## deviceManager.createDeviceManager - -createDeviceManager\(bundleName: string, callback: AsyncCallback\): void - -Creates a **DeviceManager** instance. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Bundle name of the application.

-

callback

-

AsyncCallback<DeviceManager>

-

Yes

-

Callback invoked to return the DeviceManager instance created.

-
- -- Example - - ``` - deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { - if (err) { - console.info("createDeviceManager err:" + JSON.stringify(err)); - return; - } - console.info("createDeviceManager success"); - this.dmInstance = data; - }); - ``` - - -## DeviceStateChangeAction + +## deviceManager.createDeviceManager + +createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager>): void + +Creates a **DeviceManager** instance. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of the application.| + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes| Callback invoked to return the **DeviceManager** instance created.| + +- Example + ``` + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.info("createDeviceManager err:" + JSON.stringify(err)); + return; + } + console.info("createDeviceManager success"); + this.dmInstance = data; + }); + ``` + + +## DeviceStateChangeAction Enumerates the device states. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

ONLINE

-

0

-

The device is online.

-

READY

-

1

-

The device is ready, and the device information has been synchronized.

-

OFFLINE

-

2

-

The device is offline.

-

CHANGE

-

3

-

The device information is changed.

-
- -## DeviceType - -Enumerates device types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SPEAKER

-

0x0A

-

Smart speaker.

-

PHONE

-

0x0E

-

Phone.

-

TABLET

-

0x11

-

Tablet.

-

WEARABLE

-

0x6D

-

Wearable.

-

TV

-

0x9C

-

Smart TV.

-
- -## DeviceInfo +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| ONLINE | 0 | The device is online.| +| READY | 1 | The device is ready, and the device information has been synchronized.| +| OFFLINE | 2 | The device is offline.| +| CHANGE | 3 | The device information is changed.| + + +## DeviceType + +Enumerates the device types. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| SPEAKER | 0x0A | Smart speaker.| +| PHONE | 0x0E | Phone.| +| TABLET | 0x11 | Tablet.| +| WEARABLE | 0x6D | Wearable.| +| TV | 0x9C | Smart TV.| +| CAR | 0x83 | Car.| +| UNKNOWN_TYPE | 0 | Unknown device type.| + + +## DeviceInfo Defines device information. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

deviceId

-

number

-

Yes

-

Unique device identifier.

-

deviceName

-

string

-

Yes

-

Device name.

-

deviceType

-

number

-

Yes

-

Device type.

-
- -## DeviceManager - -Creates a **DeviceManager** instance to obtain information about trusted devices and local devices. Before calling any method in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. - -### release - -release\(\): void - -Releases the **DeviceManager** instance that is no longer used. - -- Example - - ``` - dmInstance.release(); - ``` - - -### getTrustedDeviceListSync - -getTrustedDeviceListSync\(\): Array +**System capability**: SystemCapability.DistributedHardware.DeviceManager -Obtains all trusted devices synchronously. +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | number | Yes| Unique device identifier.| +| deviceName | string | Yes| Device name.| +| deviceType | number | Yes| Device type.| + + +## DeviceManager -- Return values +Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. - - - - - - - - - -

Name

-

Description

-

Array<DeviceInfo>

-

List of trusted devices obtained.

-
-- Example +### release - ``` - var deviceInfoList = dmInstance.getTrustedDeviceListSync(); - ``` +release(): void +Releases the **DeviceManager** instance that is no longer used. -### on\('deviceStateChange'\) +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Example + ``` + dmInstance.release(); + ``` + + +### getTrustedDeviceListSync + +getTrustedDeviceListSync(): Array<DeviceInfo> + +Obtains all trusted devices synchronously. -on\(type: 'deviceStateChange', callback: Callback<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Name| Description| + | -------- | -------- | + | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| + +- Example + ``` + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + ``` + + +### on('deviceStateChange') + +on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void Subscribes to changes in the device state. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is deviceStateChange, which indicates a device state change event.

-

callback

-

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

-

Yes

-

Callback invoked to return the device information and state.

-
- - -- Example - - ``` - dmInstance.on('deviceStateChange', (data) => { - console.info("deviceStateChange on:" + JSON.stringify(data)); - } - ); - ``` - - -### off\('deviceStateChange'\) - -off\(type: 'deviceStateChange', callback?: Call back<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void +**System capability**: SystemCapability.DistributedHardware.DeviceManager -Unsubscribes from changes in the device state. +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **deviceStateChange**, which indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes| Callback invoked to return the device information and state.| -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

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

-

callback

-

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

-

Yes

-

Callback used to return the device state changes.

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

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

-

callback

-

() => void

-

Yes

-

Callback invoked when a dead event of the DeviceManager service occurs.

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

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

-

callback

-

() => void

-

No

-

Callback used to return the dead event of the DeviceManager service.

-
- - -- Example - - ``` - dmInstance.off("serviceDie", () => { - console.info("serviceDie off"); +- Example + ``` + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); } - ); - ``` + ); + ``` + + +### off('deviceStateChange') + +off(type: 'deviceStateChange', callback?: Call back<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void + +Unsubscribes from changes in the device state. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **deviceStateChange** indicates an event of device state change.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes| Callback invoked to return the device information and state.| + +- Example + ``` + dmInstance.off('deviceStateChange', (data) => { + console.info('deviceStateChange' + JSON.stringify(data)); + } + ); + ``` + + +### on('serviceDie') + +on(type: 'serviceDie', callback: () => void): void + +Subscribes to dead events of the **DeviceManager** service. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | Yes| Callback invoked when a dead event of the **DeviceManager** service occurs.| + +- Example + ``` + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + } + ); + ``` + + +### off('serviceDie') + +off(type: 'serviceDie', callback?: () => void): void + +Unsubscribes from dead events of the **DeviceManager** service. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | No| Callback used to return the dead event of the **DeviceManager** service.| +- Example + ``` + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + } + ); + ``` diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index fa0eac3fef..934bcc66d0 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -29,10 +29,10 @@ Checks whether the application specified by **bundleName** is in the idle state. ``` bundleState.isIdleState("com.ohos.camera", (err, res) => { - if(err.code === 0) { - console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); - } else { + if (err) { console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); } }); ``` @@ -85,10 +85,10 @@ Queries the priority group of the current invoker application. This API uses an ``` bundleState.queryAppUsagePriorityGroup((err, res) => { - if(err.code === 0) { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); - } else { + if (err) { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); } }); ``` @@ -139,7 +139,9 @@ Queries the application usage duration statistics based on the specified start t ``` bundleState.queryBundleStateInfos(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); let i = 1; for(let key in res){ @@ -147,8 +149,6 @@ Queries the application usage duration statistics based on the specified start t console.log('BUNDLE_ACTIVE queryBundleStateInfos callback result ' + JSON.stringify(res[key])); i++; } - } else { - console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code); } }); ``` @@ -215,14 +215,14 @@ Queries the application usage duration statistics in the specified time frame at ``` bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback result ' + JSON.stringify(res[i])); } - } else { - console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); } }); ``` @@ -287,14 +287,14 @@ Queries events of all applications based on the specified start time and end tim ``` bundleState.queryBundleActiveStates(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleActiveStates callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates callback result ' + JSON.stringify(res[i])); } - } else { - console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code); } }); ``` @@ -356,14 +356,14 @@ Queries events of this application based on the specified start time and end tim ``` bundleState.queryCurrentBundleActiveStates(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback result ' + JSON.stringify(res[i])); - } - } else { - console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code); + } } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 8a787a420d..faaf19c4db 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -67,7 +67,7 @@ Obtains the default display object. ``` var displayClass = null; display.getDefaultDisplay((err, data) => { - if (err) { + if (err.code) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); return; } @@ -119,7 +119,7 @@ Obtains all the display objects. ``` display.getAllDisplay((err, data) => { - if (err) { + if (err.code) { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); return; } diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index ee8b2f2a0a..ddf747f756 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,306 +1,149 @@ -# Distributed Account Management +# Distributed Account Management ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import + +## Modules to Import ``` import account_distributedAccount from '@ohos.account.distributedAccount'; ``` -## System Capabilities +## System Capability SystemCapability.Account.OsAccount -## account\_distributedAccount.getDistributedAccountAbility +## account_distributedAccount.getDistributedAccountAbility + +getDistributedAccountAbility(): DistributedAccountAbility -getDistributedAccountAbility\(\): DistributedAccountAbility +Obtains a **DistributedAccountAbility** instance. -Obtains a **DistributedAccountAbility** instance. +- Return value + | Type| Description| + | -------- | -------- | + | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| -- Return values +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + ``` - - - - - - - - - -

Type

-

Description

-

DistributedAccountAbility

-

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

-
+## DistributedAccountAbility -- Example +Provides methods for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - ``` +### queryOsAccountDistributedInfo +queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void -## DistributedAccountAbility +Obtains distributed account information. This method uses an asynchronous callback to return the result. -Provides methods for querying and updating the login state of a distributed account. \(You must obtain a **DistributedAccountAbility** instance first.\) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) -### queryOsAccountDistributedInfo +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the distributed account information obtained.| -queryOsAccountDistributedInfo\(callback: AsyncCallback\): void +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo((err, data) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + ``` -Obtains distributed account information. This method uses an asynchronous callback to return the result. +### queryOsAccountDistributedInfo -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS or ohos.permission.DISTRIBUTED\_DATASYNC** permission is required. This permission is intended for system applications only. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<DistributedInfo>

-

Yes

-

Callback invoked to return the distributed account information.

-
- -- Example - - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo((err, data) => { - console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); - }); - ``` - - -### queryOsAccountDistributedInfo - -queryOsAccountDistributedInfo\(\): Promise +queryOsAccountDistributedInfo(): Promise<DistributedInfo> Obtains distributed account information. This method uses a promise to return the result asynchronously. -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS or ohos.permission.DISTRIBUTED\_DATASYNC** permission is required. This permission is intended for system applications only. +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) -- Return values +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| - - - - - - - - - -

Type

-

Description

-

Promise<DistributedInfo>

-

Promise used to return the result.

-
+- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); + }); + ``` -- Example +### updateOsAccountDistributedInfo - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo().then((data) => { - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); - }).catch((err) => { - console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); - }); - ``` +updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void +Updates distributed account information. This method uses an asynchronous callback to return the result. -### updateOsAccountDistributedInfo +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) -updateOsAccountDistributedInfo\(accountInfo: DistributedInfo, callback: AsyncCallback\): void +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the distributed account information is updated.| -Updates distributed account information. This method uses an asynchronous callback to return the result. +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + +### updateOsAccountDistributedInfo -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

accountInfo

-

DistributedInfo

-

Yes

-

Distributed account information.

-

callback

-

AsyncCallback<void>

-

Yes

-

Callback invoked when the distributed account information is updated.

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

Name

-

Type

-

Mandatory

-

Description

-

accountInfo

-

DistributedInfo

-

Yes

-

Distributed account information.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
- -- Example - - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { - console.log('updateOsAccountDistributedInfo Success'); - }).catch((err) => { - console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); - }); - ``` - - -## DistributedInfo +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { + console.log('updateOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +## DistributedInfo Defines distributed OS account information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

name

-

string

-

Yes

-

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

-

id

-

string

-

Yes

-

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

-

event

-

string

-

Yes

-

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

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

scalableData

-

object

-

No

-

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

-

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

-
+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a distributed account. It must be a non-null string.| +| id | string | Yes| UID of a distributed account. It must be a non-null string.| +| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index ce1692a8b2..d813b75b3e 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -26,29 +26,29 @@ Creates a **KVManager** object to manage key-value (KV) stores. This method uses | config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** object created.| - **Example** - - let kvManager; - try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } +``` +let kvManager; +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("createKVManager err: " + JSON.stringify(err)); - return; - } - console.log("createKVManager success"); - kvManager = manager; - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("createKVManager err: " + JSON.stringify(err)); + return; + } + console.log("createKVManager success"); + kvManager = manager; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ## distributedData.createKVManager @@ -72,25 +72,26 @@ Creates a **KVManager** object to manage KV stores. This method uses a promise t **Example** - let kvManager; - try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } +``` +let kvManager; +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("createKVManager success"); - kvManager = manager; - }).catch((err) => { - console.log("createKVManager err: " + JSON.stringify(err)); - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); } - + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("createKVManager success"); + kvManager = manager; + }).catch((err) => { + console.log("createKVManager err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ## KVManagerConfig @@ -103,8 +104,6 @@ Provides configuration of the **KVManager** object, including the bundle name an | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| - - ## UserInfo Defines user information. @@ -132,8 +131,6 @@ Defines the user type. Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use **createKVManager** to create a **KVManager** object. - - ### getKVStore getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void @@ -152,30 +149,30 @@ Creates and obtains a KV store. This method uses an asynchronous callback to ret **Example** - ``` - let kvStore; - let kvManager; - try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options, function (err, store) { - if (err) { - console.log("getKVStore err: " + JSON.stringify(err)); - return; - } - console.log("getKVStore success"); - kvStore = store; - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +let kvManager; +try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + securityLevel : distributedData.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.log("getKVStore err: " + JSON.stringify(err)); + return; + } + console.log("getKVStore success"); + kvStore = store; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### getKVStore @@ -200,31 +197,30 @@ Creates and obtains a KV store. This method uses a promise to return the result. | -------------------------------------- | ------------------------ | | Promise<T> <T extends KVStore> | Promise used to return the KV store created.| - **Example** - ``` - let kvStore; - let kvManager; - try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options).then((store) => { - console.log("getKVStore success"); - kvStore = store; - }).catch((err) => { - console.log("getKVStore err: " + JSON.stringify(err)); - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +let kvManager; +try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + securityLevel : distributedData.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("getKVStore success"); + kvStore = store; + }).catch((err) => { + console.log("getKVStore err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### closeKVStore8+ ### @@ -244,33 +240,33 @@ Closes a KV store. This method uses an asynchronous callback to return the resul | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned. | - **Example** - ``` - let kvStore; - let kvManager; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); - }); - } catch (e) { - console.log('closeKVStore e ' + e); - } - ``` +``` +let kvStore; +let kvManager; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, + } + try { + kvManager.getKVStore('storeId', options, async function (err, store) { + console.log('getKVStore success'); + kvStore = store; + await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { + console.log('closeKVStore success'); + }); + }); +} catch (e) { + console.log('closeKVStore e ' + e); +} +``` + ### closeKVStore8+ ### @@ -296,34 +292,34 @@ Closes a KV store. This method uses a promise to return the result. **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { - console.log('closeKVStore success'); - }).catch((err) => { - console.log('closeKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); - }); - } catch (e) { - console.log('closeKVStore e ' + e); - } - ``` +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} + try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('getKVStore success'); + kvStore = store; + await kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { + console.log('closeKVStore success'); + }).catch((err) => { + console.log('closeKVStore err ' + JSON.stringify(err)); + }); + }).catch((err) => { + console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); + }); + } catch (e) { + console.log('closeKVStore e ' + e); +} +``` ### deleteKVStore8+ ### @@ -342,33 +338,32 @@ Deletes a KV store. This method uses an asynchronous callback to return the resu | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned. | - **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('store', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { - console.log('deleteKVStore success'); - }); +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} +try { + kvManager.getKVStore('store', options, async function (err, store) { + console.log('getKVStore success'); + kvStore = store; + await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + console.log('deleteKVStore success'); }); - } catch (e) { - console.log('DeleteKVStore e ' + e); - } - ``` + }); +} catch (e) { + console.log('DeleteKVStore e ' + e); +} +``` ### deleteKVStore8+ ### @@ -394,34 +389,34 @@ Deletes a KV store. This method uses a promise to return the result. **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('deleteKVStore success'); - }).catch((err) => { - console.log('deleteKVStore err ' + JSON.stringify(err)); - }); +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storId', options).then(async (store) => { + console.log('getKVStore success'); + kvStore = store; + await kvManager.deleteKVStore('appId', 'storeId').then(() => { + console.log('deleteKVStore success'); }).catch((err) => { - console.log('getKVStore err ' + JSON.stringify(err)); + console.log('deleteKVStore err ' + JSON.stringify(err)); }); - } catch (e) { - console.log('deleteKVStore e ' + e); - } - ``` + }).catch((err) => { + console.log('getKVStore err ' + JSON.stringify(err)); + }); +} catch (e) { + console.log('deleteKVStore e ' + e); +} +``` ### getAllKVStoreId8+ ### @@ -441,17 +436,17 @@ Obtains the IDs of all the KV stores that are created using **getKvStore** and h **Example** - ``` - let kvManager; - try { - kvManager.getAllKVStoreId('appId', function (err, data) { - console.log('GetAllKVStoreId success'); - console.log('GetAllKVStoreId size = ' + data.length); - }); - } catch (e) { - console.log('GetAllKVStoreId e ' + e); - } - ``` +``` +let kvManager; +try { + kvManager.getAllKVStoreId('appId', function (err, data) { + console.log('GetAllKVStoreId success'); + console.log('GetAllKVStoreId size = ' + data.length); + }); +} catch (e) { + console.log('GetAllKVStoreId e ' + e); +} +``` ### getAllKVStoreId8+ ### @@ -477,20 +472,20 @@ Obtains the IDs of all the KV stores that are created using **getKvStore** and h **Example** - ``` - let kvManager; - try { - console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('apppId').then((data) => { - console.log('getAllKVStoreId success'); - console.log('size = ' + data.length); - }).catch((err) => { - console.log('getAllKVStoreId err ' + JSON.stringify(err)); - }); - } catch(e) { - console.log('getAllKVStoreId e ' + e); - } - ``` +``` +let kvManager; +try { + console.log('GetAllKVStoreId'); + kvManager.getAllKVStoreId('apppId').then((data) => { + console.log('getAllKVStoreId success'); + console.log('size = ' + data.length); + }).catch((err) => { + console.log('getAllKVStoreId err ' + JSON.stringify(err)); + }); +} catch(e) { + console.log('getAllKVStoreId e ' + e); +} +``` ### on8+ ### @@ -508,23 +503,21 @@ Subscribes to the **distributedDataServiceDie** events. This method uses a synch | event | 'distributedDataServiceDie' | Yes | Type of events to subscribe to. | | deathCallback | Callback<void> | Yes | Callback invoked when the distributed data service is dead. | - - **Example** - ``` - let kvManager; - try { - - console.log('KVManagerOn'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.on('distributedDataServiceDie', deathCallback); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); +``` +let kvManager; +try { + + console.log('KVManagerOn'); + const deathCallback = function () { + console.log('death callback call'); } - ``` + kvManager.on('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### off8+ ### @@ -545,19 +538,19 @@ Unsubscribes from the **distributedDataServiceDie** events. This method uses a s **Example** - ``` - let kvManager; - try { - console.log('KVManagerOff'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.off('distributedDataServiceDie', deathCallback); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); +``` +let kvManager; +try { + console.log('KVManagerOff'); + const deathCallback = function () { + console.log('death callback call'); } + kvManager.off('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} - ``` +``` ## Options @@ -573,7 +566,7 @@ Provides KV store configuration. | autoSync | boolean | No|Whether to automatically synchronize database files. By default, database files are not automatically synchronized. | | kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.| | securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set. | -| schema | [schema](#Schema8+) | No| Schema used to define the values stored in a KV store.| +| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.| ## KVStoreType @@ -589,7 +582,6 @@ Defines the KV store types. | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. | - ## SecurityLevel Defines the KV store security levels. @@ -629,8 +621,8 @@ Defines a database schema. When creating or opening a KV store, you can create a | Name | Type| Description | | --- | ---- | ----------------------- | -| root8+ | [FieldNode](#FieldNode) | JSON root object. | -| indexes8+ | Array | String array in JSON format. | +| root8+ | [FieldNode](#fieldnode8) | JSON root object. | +| indexes8+ | Array\ | String array in JSON format. | | mode8+ | number | Schema mode. | | skip8+ | number | Size of a skip of the schema. | @@ -664,9 +656,9 @@ A constructor used to create a **FieldNode** instance with a string field. **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| name | string | Yes | Value of **FieldNode**. +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | --------------- | +| name | string | Yes | Value of **FieldNode**.| ### appendChild8+ ### @@ -680,7 +672,7 @@ Appends a child node to this **FieldNode**. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| child | [FieldNode](#FieldNode) | Yes | Child node to append. | +| child | [FieldNode](#fieldnode8) | Yes | Child node to append. | **Return value** @@ -691,27 +683,25 @@ Appends a child node to this **FieldNode**. **Example** - ``` - import ddm from '@ohos.data.distributedData'; - try { - let node = new ddm.FieldNode("root"); - let child1 = new ddm.FieldNode("child1"); - let child2 = new ddm.FieldNode("child2"); - let child3 = new ddm.FieldNode("child3"); - node.appendChild(child1); - node.appendChild(child2); - node.appendChild(child3); - console.log("appendNode " + node.toJson()); - child1 = null; - child2 = null; - child3 = null; - node = null; - } catch (e) { - console.log("AppendChild " + e); - } - ``` - - +``` +import ddm from '@ohos.data.distributedData'; +try { + let node = new ddm.FieldNode("root"); + let child1 = new ddm.FieldNode("child1"); + let child2 = new ddm.FieldNode("child2"); + let child3 = new ddm.FieldNode("child3"); + node.appendChild(child1); + node.appendChild(child2); + node.appendChild(child3); + console.log("appendNode " + node.toJson()); + child1 = null; + child2 = null; + child3 = null; + node = null; +} catch (e) { + console.log("AppendChild " + e); +} +``` ## KvStoreResultSet8+ ## @@ -735,23 +725,22 @@ Obtains the number of rows in the result set. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const count = resultSet.getCount(); - console.log("GetCount " + count); - } catch (e) { - console.log("GetCount fail " + e); - } - ``` - +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const count = resultSet.getCount(); + console.log("GetCount " + count); +} catch (e) { + console.log("GetCount fail " + e); +} +``` ### getPosition8+ ### @@ -769,22 +758,22 @@ Obtains the current data read position (position from which data is read) in the **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const positon = resultSet.getPosition(); - console.log("getPosition " + positon); - } catch (e) { - console.log("GetPosition fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const position = resultSet.getPosition(); + console.log("getPosition " + position); +} catch (e) { + console.log("GetPosition fail " + e); +} +``` ### moveToFirst8+ ### @@ -803,22 +792,22 @@ Moves the data read position to the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToFirst(); - console.log("moveToFirst " + moved); - } catch (e) { - console.log("MoveToFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToFirst(); + console.log("moveToFirst " + moved); +} catch (e) { + console.log("MoveToFirst fail " + e); +} +``` ### moveToLast8+ ### @@ -837,22 +826,22 @@ Moves the data read position to the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToLast(); - console.log("moveToLast " + moved); - } catch (e) { - console.log("moveToLast fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToLast(); + console.log("moveToLast " + moved); +} catch (e) { + console.log("moveToLast fail " + e); +} +``` ### moveToNext8+ ### @@ -871,22 +860,22 @@ Moves the data read position to the next row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToNext(); - console.log("moveToNext " + moved); - } catch (e) { - console.log("moveToNext fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToNext(); + console.log("moveToNext " + moved); +} catch (e) { + console.log("moveToNext fail " + e); +} +``` ### moveToPrevious8+ ### @@ -905,22 +894,22 @@ Moves the data read position to the previous row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToPrevious(); - console.log("moveToPrevious " + moved); - } catch (e) { - console.log("moveToPrevious fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToPrevious(); + console.log("moveToPrevious " + moved); +} catch (e) { + console.log("moveToPrevious fail " + e); +} +``` ### move8+ ### @@ -945,22 +934,22 @@ Moves the data read position with the specified offset from the current position **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.move(); - console.log("move " + moved); - } catch (e) { - console.log("move fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.move(); + console.log("move " + moved); +} catch (e) { + console.log("move fail " + e); +} +``` ### moveToPosition8+ ### @@ -985,22 +974,22 @@ Moves the data read position from 0 to an absolute position. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToPosition(); - console.log("moveToPosition " + moved); - } catch (e) { - console.log("moveToPosition fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToPosition(); + console.log("moveToPosition " + moved); +} catch (e) { + console.log("moveToPosition fail " + e); +} +``` ### isFirst8+ ### @@ -1019,22 +1008,22 @@ Checks whether the data read position is the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isFirst(); - console.log("isFirst " + moved); - } catch (e) { - console.log("isFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isFirst(); + console.log("isFirst " + moved); +} catch (e) { + console.log("isFirst fail " + e); +} +``` ### isLast8+ ### @@ -1053,23 +1042,22 @@ Checks whether the data read position is the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isLast(); - console.log("isLast " + moved); - } catch (e) { - console.log("isLast fail " + e); - } - ``` - +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isLast(); + console.log("isLast " + moved); +} catch (e) { + console.log("isLast fail " + e); +} +``` ### isBeforeFirst8+ ### @@ -1087,22 +1075,22 @@ Checks whether the data read position is before the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isBeforeFirst(); - console.log("isBeforeFirst " + moved); - } catch (e) { - console.log("isBeforeFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isBeforeFirst(); + console.log("isBeforeFirst " + moved); +} catch (e) { + console.log("isBeforeFirst fail " + e); +} +``` ### isAfterLast8+ ### @@ -1121,22 +1109,22 @@ Checks whether the data read position is after the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isAfterLast(); - console.log("isAfterLast " + moved); - } catch (e) { - console.log("isAfterLast fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isAfterLast(); + console.log("isAfterLast " + moved); +} catch (e) { + console.log("isAfterLast fail " + e); +} +``` ### getEntry8+ ### @@ -1155,23 +1143,23 @@ Obtains a KV pair. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToNext(); - const entry = resultSet.getEntry(); - console.log("getEntry " + JSON.stringify(entry)); - } catch (e) { - console.log("getEntry fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToNext(); + const entry = resultSet.getEntry(); + console.log("getEntry " + JSON.stringify(entry)); +} catch (e) { + console.log("getEntry fail " + e); +} +``` ## Query8+ ## @@ -1206,18 +1194,18 @@ Resets the **Query** object that contains common query options. **Example** - ``` - try { - let query = new distributedData.Query(); - query.equalTo("key", "value"); - console.log("query is " + query.getSqlLike()); - query.reset(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("simply calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.equalTo("key", "value"); + console.log("query is " + query.getSqlLike()); + query.reset(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("simply calls should be ok :" + e); +} +``` ### equalTo8+ ### @@ -1243,16 +1231,16 @@ Creates a **Query** object to match the specified field whose value is equal to **Example** - ``` - try { - let query = new distributedData.Query(); - query.equalTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.equalTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notEqualTo8+ ### @@ -1278,16 +1266,16 @@ Creates a **Query** object to match the specified field whose value is not equal **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### greaterThan8+ ### @@ -1303,7 +1291,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1313,16 +1301,16 @@ Creates a **Query** object to match the specified field whose value is greater t **Example** - ``` - try { - let query = new distributedData.Query(); - query.greaterThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.greaterThan("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### lessThan8+ ### @@ -1338,7 +1326,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1348,16 +1336,16 @@ Creates a **Query** object to match the specified field whose value is less than **Example** - ``` - try { - let query = new distributedData.Query(); - query.lessThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.lessThan("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### greaterThanOrEqualTo8+ ### @@ -1373,7 +1361,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1383,16 +1371,16 @@ Creates a **Query** object to match the specified field whose value is greater t **Example** - ``` - try { - let query = new distributedData.Query(); - query.greaterThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.greaterThanOrEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### lessThanOrEqualTo8+ ### @@ -1408,7 +1396,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1418,16 +1406,16 @@ Creates a **Query** object to match the specified field whose value is less than **Example** - ``` - try { - let query = new distributedData.Query(); - query.lessThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.lessThanOrEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### isNull8+ ### @@ -1453,16 +1441,16 @@ Creates a **Query** object to match the specified field whose value is **null**. **Example** - ``` - try { - let query = new distributedData.Query(); - query.isNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.isNull("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### inNumber8+ ### @@ -1487,19 +1475,18 @@ Creates a **Query** object to match the specified field whose value is within th | ------ | ------- | | [Query](#query8) |**Query** object Created.| - **Example** - ``` - try { - let query = new distributedData.Query(); - query.inNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.inNumber("field", [0, 1]); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### inString8+ ### @@ -1525,16 +1512,16 @@ Creates a **Query** object to match the specified field whose value is within th **Example** - ``` - try { - let query = new distributedData.Query(); - query.inString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.inString("field", ['test1', 'test2']); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notInNumber8+ ### @@ -1560,16 +1547,16 @@ Creates a **Query** object to match the specified field whose value is not withi **Example** - ``` - try { - let query = new distributedData.Query(); - query.notInNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notInNumber("field", [0, 1]); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notInString8+ ### @@ -1595,16 +1582,16 @@ Creates a **Query** object to match the specified field whose value is not withi **Example** - ``` - try { - let query = new distributedData.Query(); - query.notInString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notInString("field", ['test1', 'test2']); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### like8+ ### @@ -1630,16 +1617,16 @@ Creates a **Query** object to match the specified field whose value is similar t **Example** - ``` - try { - let query = new distributedData.Query(); - query.like("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.like("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### unlike8+ ### @@ -1665,16 +1652,16 @@ Creates a **Query** object to match the specified field whose value is not simil **Example** - ``` - try { - let query = new distributedData.Query(); - query.unlike("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.unlike("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### and8+ ### @@ -1693,18 +1680,18 @@ Creates a **Query** object with the AND condition. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.and(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value1"); + query.and(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### or8+ ### @@ -1723,18 +1710,18 @@ Creates a **Query** object with the OR condition. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.or(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value1"); + query.or(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### orderByAsc8+ ### @@ -1759,17 +1746,17 @@ Creates a **Query** object to sort the query results in ascending order. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByAsc("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.orderByAsc("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### orderByDesc8+ ### @@ -1792,20 +1779,19 @@ Creates a **Query** object to sort the query results in descending order. | ------ | ------- | | [Query](#query8) |**Query** object Created.| - **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByDesc("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.orderByDesc("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### limit8+ ### @@ -1831,17 +1817,17 @@ Creates a **Query** object to specify the number of results and where to start. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.limit("total", "offset"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.limit("total", "offset"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### isNotNull8+ ### @@ -1866,16 +1852,16 @@ Creates a **Query** object with a specified field that is not null. **Example** - ``` - try { - let query = new distributedData.Query(); - query.isNotNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.isNotNull("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### beginGroup8+ ### @@ -1894,18 +1880,18 @@ Creates a **Query** object for a query condition group with a left parenthesis. **Example** - ``` - try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### endGroup8+ ### @@ -1924,18 +1910,18 @@ Creates a **Query** object for a query condition group with a right parenthesis. **Example** - ``` - try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### prefixKey8+ ### @@ -1960,17 +1946,17 @@ Creates a **Query** object with a specified key prefix. **Example** - ``` - try { - let query = new distributedData.Query(); - query.prefixKey("$.name"); - query.prefixKey("0"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.prefixKey("$.name"); + query.prefixKey("0"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### setSuggestIndex8+ ### @@ -1995,17 +1981,17 @@ Creates a **Query** object with an index preferentially used for query. **Example** - ``` - try { - let query = new distributedData.Query(); - query.setSuggestIndex("$.name"); - query.setSuggestIndex("0"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.setSuggestIndex("$.name"); + query.setSuggestIndex("0"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### deviceId8+ ### @@ -2031,15 +2017,15 @@ Creates a **Query** object with the device ID as the key prefix. **Example** - ``` - try { - let query = new distributedData.Query(); - query.deviceId("deviceId"); - console.log("query is " + query.getSqlLike()); - } catch (e) { - console.log("should be ok on Method Chaining : " + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.deviceId("deviceId"); + console.log("query is " + query.getSqlLike()); +} catch (e) { + console.log("should be ok on Method Chaining : " + e); +} +``` ### getSqlLike8+ ### @@ -2058,15 +2044,15 @@ Obtains the query statement of this **Query** object. **Example** - ``` - try { - let query = new distributedData.Query(); - let sql1 = query.getSqlLike(); - console.log("GetSqlLike sql=" + sql1); - } catch (e) { - console.log("dumplicated calls should be ok : " + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + let sql1 = query.getSqlLike(); + console.log("GetSqlLike sql=" + sql1); +} catch (e) { + console.log("dumplicated calls should be ok : " + e); +} +``` ## KVStore @@ -2089,26 +2075,26 @@ Adds a KV pair of the specified type to this KV store. This method uses an async | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### put @@ -2132,23 +2118,22 @@ Adds a KV pair of the specified type to this KV store. This method uses a promis | ------ | ------- | | Promise<void> |Promise used to return the result.| - **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### delete @@ -2168,29 +2153,29 @@ Deletes a KV pair from this KV store. This method uses an asynchronous callback **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); + console.log("delete err: " + JSON.stringify(err)); return; } - console.log("put success"); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("delete err: " + JSON.stringify(err)); - return; - } - console.log("delete success"); - }); + console.log("delete success"); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### delete @@ -2215,25 +2200,25 @@ Deletes a KV pair from this KV store. This method uses a promise to return the r **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("delete success"); - }).catch((err) => { - console.log("delete err: " + JSON.stringify(err)); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("delete success"); }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); + console.log("delete err: " + JSON.stringify(err)); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### on @@ -2248,19 +2233,18 @@ Subscribes to data changes of the specified type. This method uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |'dataChange' | Yes |Type of the events. | +| event |'dataChange' | Yes |Type of the events. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | | observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return the result.| - **Example** - ``` - let kvStore; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); - }); - ``` +``` +let kvStore; +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); +``` ### on @@ -2275,18 +2259,17 @@ Subscribes to data synchronization completion events. This method uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |'syncComplete' | Yes |Type of the events. | +| event |'syncComplete' | Yes |Type of the events. | | syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the result. | - **Example** - ``` - let kvStore; - kvStore.on('syncComplete', function (data) { - console.log("syncComplete callback call data: " + data); - }); - ``` +``` +let kvStore; +kvStore.on('syncComplete', function (data) { + console.log("syncComplete callback call data: " + data); +}); +``` ### off8+ @@ -2305,15 +2288,15 @@ Unsubscribes from data change events. This method uses a synchronous callback to **Example** - ``` - let kvStore; - kvStore.on('dataChange', function (data) { - console.log("syncComplete callback call data: " + data); - }); - kvStore.off('dataChange', function (data) { - console.log("syncComplete callback call data: " + data); - }); - ``` +``` +let kvStore; +kvStore.on('dataChange', function (data) { + console.log("syncComplete callback call data: " + data); +}); +kvStore.off('dataChange', function (data) { + console.log("syncComplete callback call data: " + data); +}); +``` ### putBatch8+ @@ -2333,35 +2316,34 @@ Inserts KV pairs in batches to this KV store. This method uses an asynchronous c **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### putBatch8+ @@ -2386,37 +2368,37 @@ Inserts KV pairs in batches to this KV store. This method uses a promise to retu **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('PutBatch ' + JSON.stringify(entries)); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### deleteBatch8+ @@ -2436,34 +2418,34 @@ Deletes KV pairs in batches from this KV store. This method uses an asynchronous **Example** - ``` - let kvStore; - try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); - keys.push(key + i); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.deleteBatch(keys, async function (err,data) { - console.log('deleteBatch success'); - }); - }); - }catch(e) { - console.log('DeleteBatch e ' + e); + entries.push(entry); + keys.push(key + i); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.deleteBatch(keys, async function (err,data) { + console.log('deleteBatch success'); + }); + }); +}catch(e) { + console.log('DeleteBatch e ' + e); +} +``` ### deleteBatch8+ ### @@ -2488,38 +2470,38 @@ Deletes KV pairs in batches from this KV store. This method uses a promise to re **Example** - ``` - let kvStore; - try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); - keys.push(key + i); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.deleteBatch(keys).then((err) => { - console.log('deleteBatch success'); - }).catch((err) => { - console.log('deleteBatch fail ' + JSON.stringify(err)); - }); + entries.push(entry); + keys.push(key + i); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.deleteBatch(keys).then((err) => { + console.log('deleteBatch success'); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('deleteBatch fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('DeleteBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('DeleteBatch e ' + e); +} +``` ### startTransaction8+ ### @@ -2538,40 +2520,40 @@ Starts the transaction in this KV store. This method uses an asynchronous callba **Example** - ``` - let kvStore; - function putBatchString(len, prefix) { - let entries = []; - for (var i = 0; i < len; i++) { - var entry = { - key : prefix + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +function putBatchString(len, prefix) { + let entries = []; + for (var i = 0; i < len; i++) { + var entry = { + key : prefix + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - return entries; + entries.push(entry); } - try { - var count = 0; - kvStore.on('dataChange', 0, function (data) { - console.log('startTransaction 0' + data) - count++; - }); - kvStore.startTransaction(async function (err,data) { - console.log('startTransaction success'); - let entries = putBatchString(10, 'batch_test_string_key'); - console.log('entries: ' + JSON.stringify(entries)); - await kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - }); + return entries; +} +try { + var count = 0; + kvStore.on('dataChange', 0, function (data) { + console.log('startTransaction 0' + data) + count++; + }); + kvStore.startTransaction(async function (err,data) { + console.log('startTransaction success'); + let entries = putBatchString(10, 'batch_test_string_key'); + console.log('entries: ' + JSON.stringify(entries)); + await kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); }); - }catch(e) { - console.log('startTransaction e ' + e); - } - ``` + }); +}catch(e) { + console.log('startTransaction e ' + e); +} +``` ### startTransaction8+ ### @@ -2590,23 +2572,23 @@ Starts the transaction in this KV store. This method uses a promise to return th **Example** - ``` - let kvStore; - try { - var count = 0; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log('startTransaction ' + JSON.stringify(data)); - count++; - }); - kvStore.startTransaction().then(async (err) => { - console.log('startTransaction success'); - }).catch((err) => { - console.log('startTransaction fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('startTransaction e ' + e); - } - ``` +``` +let kvStore; +try { + var count = 0; + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { + console.log('startTransaction ' + JSON.stringify(data)); + count++; + }); + kvStore.startTransaction().then(async (err) => { + console.log('startTransaction success'); + }).catch((err) => { + console.log('startTransaction fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('startTransaction e ' + e); +} +``` ### commit8+ ### @@ -2625,20 +2607,20 @@ Commits the transaction in this KV store. This method uses an asynchronous callb **Example** - ``` - let kvStore; - try { - kvStore.commit(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); - }catch(e) { - console.log('Commit e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.commit(function (err,data) { + if (err == undefined) { + console.log('commit success'); + } else { + console.log('commit fail'); + } + }); +}catch(e) { + console.log('Commit e ' + e); +} +``` ### commit8+ ### @@ -2657,18 +2639,18 @@ Commits the transaction in this KV store. This method uses a promise to return t **Example** - ``` - let kvStore; - try { - kvStore.commit().then(async (err) => { - console.log('commit success'); - }).catch((err) => { - console.log('commit fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('Commit e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.commit().then(async (err) => { + console.log('commit success'); + }).catch((err) => { + console.log('commit fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('Commit e ' + e); +} +``` ### rollback8+ ### @@ -2687,20 +2669,20 @@ Rolls back the transaction in this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - try { - kvStore.rollback(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); - }catch(e) { - console.log('Rollback e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.rollback(function (err,data) { + if (err == undefined) { + console.log('commit success'); + } else { + console.log('commit fail'); + } + }); +}catch(e) { + console.log('Rollback e ' + e); +} +``` ### rollback8+ ### @@ -2719,18 +2701,18 @@ Rolls back the transaction in this KV store. This method uses a promise to retur **Example** - ``` - let kvStore; - try { - kvStore.rollback().then(async (err) => { - console.log('rollback success'); - }).catch((err) => { - console.log('rollback fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('Rollback e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.rollback().then(async (err) => { + console.log('rollback success'); + }).catch((err) => { + console.log('rollback fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('Rollback e ' + e); +} +``` ### enableSync8+ ### @@ -2750,20 +2732,20 @@ Sets data synchronization, which can be enabled or disable. This method uses an **Example** - ``` - let kvStore; - try { - kvStore.enableSync(true, function (err,data) { - if (err == undefined) { - console.log('enableSync success'); - } else { - console.log('enableSync fail'); - } - }); - }catch(e) { - console.log('EnableSync e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.enableSync(true, function (err,data) { + if (err == undefined) { + console.log('enableSync success'); + } else { + console.log('enableSync fail'); + } + }); +}catch(e) { + console.log('EnableSync e ' + e); +} +``` ### enableSync8+ ### @@ -2788,18 +2770,18 @@ Enables or disables data synchronization. This method uses a promise to return t **Example** - ``` - let kvStore; - try { - kvStore.enableSync(true).then((err) => { - console.log('enableSync success'); - }).catch((err) => { - console.log('enableSync fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('EnableSync e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.enableSync(true).then((err) => { + console.log('enableSync success'); + }).catch((err) => { + console.log('enableSync fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('EnableSync e ' + e); +} +``` ### setSyncRange8+ ### @@ -2820,18 +2802,18 @@ Sets the data synchronization range. This method uses an asynchronous callback t **Example** - ``` - let kvStore; - try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { - console.log('SetSyncRange put success'); - }); - }catch(e) { - console.log('SetSyncRange e ' + e); - } - ``` +``` +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { + console.log('SetSyncRange put success'); + }); +}catch(e) { + console.log('SetSyncRange e ' + e); +} +``` ### setSyncRange8+ ### @@ -2858,20 +2840,20 @@ Sets the data synchronization range. This method uses a promise to return the re **Example** - ``` - let kvStore; - try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('setSyncRange success'); - }).catch((err) => { - console.log('delete fail ' + err); - }); - }catch(e) { - console.log('SetSyncRange e ' + e); - } - ``` +``` +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + console.log('setSyncRange success'); + }).catch((err) => { + console.log('delete fail ' + err); + }); +}catch(e) { + console.log('SetSyncRange e ' + e); +} +``` ## SubscribeType @@ -2958,34 +2940,34 @@ Obtains the value of a specified key. This method uses an asynchronous callback | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array / string / boolean / number>) | Yes |Callback used to return the value obtained. | +| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback used to return the value obtained. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log("get success data: " + data); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { + console.log("get success data: " + data); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### get -get(key: string): Promise<Uint8Array | string | boolean | number> +get(key: string): Promise<Uint8Array | string | boolean | number> Obtains the value of a specified key. This method uses a promise to return the result. @@ -3002,30 +2984,29 @@ Obtains the value of a specified key. This method uses a promise to return the r | Type | Description | | ------ | ------- | -|Promise<Uint8Array / string / boolean / number> |Promise used to return the value obtained.| - +|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("get success data: " + data); - }).catch((err) => { - console.log("get err: " + JSON.stringify(err)); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("get success data: " + data); }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); + console.log("get err: " + JSON.stringify(err)); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### getEntries8+ ### @@ -3040,37 +3021,37 @@ Obtains the KV pairs that match the specified key prefix. This method uses an as | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<Entry[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_number_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.INTEGER, - value : 222 - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_number_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.INTEGER, + value : 222 } - entries.push(entry); } - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_number_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_number_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -3095,40 +3076,40 @@ Obtains the KV pairs that match the specified key prefix. This method uses a pro **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + entries); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); + console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -3144,42 +3125,42 @@ Obtains the KV pairs that match the specified **Query** object. This method uses | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<Entry[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -3204,39 +3185,39 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getResultSet8+ ### @@ -3256,36 +3237,36 @@ Obtains the result set with the specified key prefix from this single KV store. **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('GetResultSet putBatch success'); - await kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('GetResultSet closeResultSet success'); - }) - }); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('GetResultSet putBatch success'); + await kvStore.getResultSet('batch_test_string_key', async function (err, result) { + console.log('GetResultSet getResultSet success'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + console.log('GetResultSet closeResultSet success'); + }) + }); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -3310,42 +3291,42 @@ Obtains the result set with the specified key prefix from this single KV store. **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResult closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResult e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('PutBatch putBatch fail ' + JSON.stringify(err)); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('GetResult getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('GetResult closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResult e ' + e); +} +``` ### getResultSet8+ ### @@ -3365,35 +3346,35 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSet(query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -3418,40 +3399,39 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` - + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log(' getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -3470,21 +3450,21 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('closeResultSet success'); + } else { + console.log('closeResultSet fail'); + } + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -3509,19 +3489,19 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### getResultSize8+ ### @@ -3541,33 +3521,33 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSize(query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -3592,37 +3572,37 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### removeDeviceData8+ ### @@ -3642,29 +3622,29 @@ Deletes data of a device. This method uses an asynchronous callback to return th **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('put success'); + const deviceid = 'no_exist_device_id'; + await kvStore.removeDeviceData(deviceid, async function (err,data) { + if (err == undefined) { + console.log('removeDeviceData success'); + } else { + console.log('removeDeviceData fail'); + await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData get success'); + }); + } }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### removeDeviceData8+ ### @@ -3689,31 +3669,31 @@ Deletes data of a device. This method uses a promise to return the result. **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('removeDeviceData put success'); - }).catch((err) => { - console.log('put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('removeDeviceData put success'); + }).catch((err) => { + console.log('put fail ' + JSON.stringify(err)); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('removeDeviceData success'); + }).catch((err) => { + console.log('removeDeviceData fail ' + JSON.stringify(err)); + }); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('get success data:' + data); + }).catch((err) => { + console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### on8+ ### @@ -3733,30 +3713,30 @@ Subscribes to the synchronization completion events. This method uses a synchron **Example** - ``` - let kvStore; - const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; - const VALUE_TEST_FLOAT_ELEMENT = 321.12; - try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); - }catch(e) { - console.log('syncComplete put e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log('syncComplete ' + data) + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('syncComplete put success'); + }).catch((error) => { + console.log('syncComplete put fail ' + error); + }); +}catch(e) { + console.log('syncComplete put e ' + e); +} +``` ### off8+ ### off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This method uses a synchronization callback to return the result. +Unsubscribes from the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3767,21 +3747,20 @@ Unsubscribes from the synchronization completion events. This method uses a sync | event |'syncComplete' | Yes |Event triggered when the synchronization is complete. | | syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - **Example** - ``` - let kvStore; - try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); - }catch(e) { - console.log('syncComplete e ' + e); - } - ``` +``` +let kvStore; +try { + const func = function (data) { + console.log('syncComplete ' + data) + }; + kvStore.on('syncComplete', func); + kvStore.off('syncComplete', func); +}catch(e) { + console.log('syncComplete e ' + e); +} +``` ### sync @@ -3789,6 +3768,7 @@ Unsubscribes from the synchronization completion events. This method uses a sync sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3802,10 +3782,10 @@ Manually triggers KV store synchronization synchronously. **Example** - ``` - let kvStore; - kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); - ``` +``` +let kvStore; +kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); +``` ### setSyncParam8+ ### @@ -3822,20 +3802,19 @@ Sets the default delay of database synchronization. This method uses an asynchro | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | - **Example** - ``` - let kvStore; - try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { - console.log('SetSyncParam put success'); - }); - }catch(e) { - console.log('testSingleKvStoreSetSyncParam e ' + e); - } - ``` +``` +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { + console.log('SetSyncParam put success'); + }); +}catch(e) { + console.log('testSingleKvStoreSetSyncParam e ' + e); +} +``` ### setSyncParam8+ ### @@ -3861,19 +3840,19 @@ Sets the default delay of database synchronization. This method uses a promise t **Example** - ``` - let kvStore; - try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('SetSyncParam put success'); - }).catch((err) => { - console.log('SetSyncParam put fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('SetSyncParam e ' + e); - } - ``` +``` +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + console.log('SetSyncParam put success'); + }).catch((err) => { + console.log('SetSyncParam put fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('SetSyncParam e ' + e); +} +``` ### getSecurityLevel8+ ### @@ -3892,16 +3871,16 @@ Obtains the security level of this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - try { - kvStore.getSecurityLevel(function (err,data) { - console.log('getSecurityLevel success'); - }); - }catch(e) { - console.log('GetSecurityLeve e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.getSecurityLevel(function (err,data) { + console.log('getSecurityLevel success'); + }); +}catch(e) { + console.log('GetSecurityLeve e ' + e); +} +``` ### getSecurityLevel8+ ### @@ -3918,21 +3897,20 @@ Obtains the security level of this KV store. This method uses a promise to retur | ------ | ------- | |Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| - **Example** - ``` - let kvStore; - try { - kvStore.getSecurityLevel().then((data) => { - console.log(' getSecurityLevel success'); - }).catch((err) => { - console.log('getSecurityLevel fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetSecurityLeve e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.getSecurityLevel().then((data) => { + console.log(' getSecurityLevel success'); + }).catch((err) => { + console.log('getSecurityLevel fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetSecurityLeve e ' + e); +} +``` ## DeviceKVStore8+ ## @@ -3947,7 +3925,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|num Obtains the string value that matches the specified key for a device. This method uses an asynchronous callback to return the result. -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** @@ -3955,26 +3933,25 @@ Obtains the string value that matches the specified key for a device. This metho | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | key |string | Yes |Key to match. | -| callback |AsyncCallback<boolean/string/number/Uint8Array> | Yes |Callback used to return the value obtained. | - +| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try{ - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log('get success'); - }); - }) - }catch(e) { - console.log('get e' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try{ + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('put success'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { + console.log('get success'); + }); + }) +}catch(e) { + console.log('get e' + e); +} +``` ### get8+ ### @@ -4000,25 +3977,25 @@ Obtains the string value that matches the specified key for a device. This metho **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log(' put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success'); - }).catch((err) => { - console.log('get fail ' + JSON.stringify(err)); - }); - }).catch((error) => { - console.log('put error' + error); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + console.log(' put success'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('get success'); + }).catch((err) => { + console.log('get fail ' + JSON.stringify(err)); }); - } catch (e) { - console.log('Get e ' + e); - } - ``` + }).catch((error) => { + console.log('put error' + error); + }); +} catch (e) { + console.log('Get e ' + e); +} +``` ### getEntries8+ ### @@ -4039,34 +4016,34 @@ Obtains the KV pairs that match the specified key prefix for a device. This meth **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + entries); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -4092,40 +4069,40 @@ Obtains the KV pairs that match the specified key prefix for a device. This meth **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + entries); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); + console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -4145,40 +4122,40 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - expect(err == undefined).assertTrue(); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getEntries(query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + expect(err == undefined).assertTrue(); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getEntries(query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4203,40 +4180,40 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4257,40 +4234,40 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - expect(err == undefined).assertTrue(); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }) - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + expect(err == undefined).assertTrue(); + var query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + await kvStore.getEntries('localDeviceId', query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4316,41 +4293,41 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + var query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + await kvStore.getEntries('localDeviceId', query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getResultSet8+ ### @@ -4371,21 +4348,21 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }catch(e) { - console.log('GetResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4411,25 +4388,25 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4449,39 +4426,39 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getResultSet(query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4506,46 +4483,46 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + err); - }); - const query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.getResultSet(query).then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + err); + }); + const query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.getResultSet(query).then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4566,38 +4543,38 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSet('localDeviceId', query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4623,47 +4600,47 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('GetResultSet putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResultSet closeResultSet success'); - }).catch((err) => { - console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); - }); - - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('GetResultSet putBatch success'); + }).catch((err) => { + console.log('PutBatch putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('GetResultSet getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('GetResultSet closeResultSet success'); + }).catch((err) => { + console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); + }); + +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -4683,22 +4660,22 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + console.log('CloseResultSet success'); + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('closeResultSet success'); + } else { + console.log('closeResultSet fail'); + } + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -4723,20 +4700,20 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + console.log('CloseResultSet success'); + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### getResultSize8+ ### @@ -4756,34 +4733,34 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getResultSize(query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4808,38 +4785,38 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.getResultSize(query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4860,33 +4837,33 @@ Obtains the number of results that matches the specified **Query** object for a **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4912,37 +4889,37 @@ Obtains the number of results that matches the specified **Query** object for a **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - var query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + var query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### removeDeviceData8+ ### @@ -4962,29 +4939,29 @@ Removes data of a device from this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData put success'); - const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData put success'); + const deviceid = 'no_exist_device_id'; + await kvStore.removeDeviceData(deviceid, async function (err,data) { + if (err == undefined) { + console.log('removeDeviceData success'); + } else { + console.log('removeDeviceData fail'); + await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData get success'); + }); + } }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### removeDeviceData8+ ### @@ -5009,31 +4986,31 @@ Removes data of a device from this KV store. This method uses a promise to retur **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('RemoveDeviceData put success'); - }).catch((err) => { - console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('RemoveDeviceData get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('RemoveDeviceData put success'); + }).catch((err) => { + console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('removeDeviceData success'); + }).catch((err) => { + console.log('removeDeviceData fail ' + JSON.stringify(err)); + }); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('RemoveDeviceData get success data:' + data); + }).catch((err) => { + console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### sync8+ ### @@ -5041,6 +5018,7 @@ Removes data of a device from this KV store. This method uses a promise to retur sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5052,31 +5030,30 @@ Manually triggers KV store synchronization synchronously. | mode |[SyncMode](#syncmode) | Yes |Data synchronization mode, which can be **PUSH**, **PULL**, or **PUSH_PULL**. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | - **Example** - ``` - let kvStore; - const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; - const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; - try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - kvStore.sync(devices, mode); - }); - }catch(e) { - console.log('Sync e' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { + console.log('Sync put success'); + const devices = ['deviceList']; + const mode = distributedData.SyncMode.PULL_ONLY; + kvStore.sync(devices, mode); + }); +}catch(e) { + console.log('Sync e' + e); +} +``` ### on8+ ### -on(event: 'syncComplete', syncCallback: Callback<Arrary<[string, number]>>): void +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void Subscribes to the synchronization completion events. This method uses a synchronous callback to return the result. @@ -5087,25 +5064,26 @@ Subscribes to the synchronization completion events. This method uses a synchron | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| -| syncCallback |Callback { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); - }catch(e) { - console.log('syncComplete put e ' + e); - } - ``` + +``` +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log('syncComplete ' + data) + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('syncComplete put success'); + }).catch((error) => { + console.log('syncComplete put fail ' + error); + }); +}catch(e) { + console.log('syncComplete put e ' + e); +} +``` ### off8+ ### @@ -5121,23 +5099,22 @@ Unsubscribes from the synchronization completion events. This method uses a sync | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| -| syncCallback |Callback ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements event subscription, unsubscription, and triggering. - - -## Usage - - -Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. - - - -```js -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - } -} -``` - - -## EventHub.on - -on(event: string, callback: Function): void; - -Subscribes to an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | Yes| Callback invoked when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", () => { - console.log("call anonymous func 1"); - }); - // Result - // func1 is called - // call anonymous func 1 - this.context.eventHub.emit("123"); - } - func1() { - console.log("func1 is called"); - } - } - ``` - - -## EventHub.off - -off(event: string, callback?: Function): void; - -Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.off("123", this.func1); // Unsubscribe from func1. - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", this.func2); - this.context.eventHub.off("123"); // Unsubscribe from func1 and func2. - } - func1() { - console.log("func1 is called"); - } - func2() { - console.log("func2 is called"); - } - } - ``` - - -## EventHub.emit - -emit(event: string, ...args: Object[]): void; - -Triggers an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - // Result - // func1 is called,undefined,undefined - this.context.eventHub.emit("123"); - // Result - // func1 is called,1,undefined - this.context.eventHub.emit("123", 1); - // Result - // func1 is called,1,2 - this.context.eventHub.emit("123", 1, 2); - } - func1(a: string, b: string) { - console.log("func1 is called," + a + "," + b); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-extension-context.md index 5a9466444c..3a18f757b3 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -1,7 +1,7 @@ # ExtensionContext > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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. Implements the extension context. This module is inherited from **Context**. @@ -9,6 +9,8 @@ Implements the extension context. This module is inherited from **Context**. ## Attributes +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core | +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP. | diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index e1bae18281..f5f75e537f 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -1,7 +1,7 @@ # ExtensionRunningInfo > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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. Provides extension running information. @@ -26,15 +26,15 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an extension.| -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Extension start time.| -| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](#bundle-extensionabilitytype) | Yes| No| Extension type.| +| extension | ElementName | Yes| No| Information that matches an extension.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| startTime | number | Yes| No| Extension start time.| +| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| +| type | [bundle.ExtensionAbilityType](#bundleextensionabilitytype) | Yes| No| Extension type.| ## bundle.ExtensionAbilityType @@ -45,13 +45,13 @@ Enumerates extension types. | Name| Value| Description| | -------- | -------- | -------- | -| FORM | 0 | Extension information of the form type. | -| WORK_SCHEDULER | 1 | Extension information of the work scheduler type. | -| INPUT_METHOD | 2 | Extension information of the input method type. | -| SERVICE | 3 | Extension information of the service type. | -| ACCESSIBILITY | 4 | Extension information of the accessibility type. | -| DATA_SHARE | 5 | Extension information of the data share type. | -| FILE_SHARE | 6 | Extension information of the file share type. | -| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type. | -| WALLPAPER | 8 | Extension information of the wallpaper type. | -| UNSPECIFIED | 9 | Extension information of the unspecified type. | +| FORM | 0 | Extension information of the form type.< | +| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.< | +| INPUT_METHOD | 2 | Extension information of the input method type.< | +| SERVICE | 3 | Extension information of the service type.< | +| ACCESSIBILITY | 4 | Extension information of the accessibility type.< | +| DATA_SHARE | 5 | Extension information of the data share type.< | +| FILE_SHARE | 6 | Extension information of the file share type.< | +| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.< | +| WALLPAPER | 8 | Extension information of the wallpaper type.< | +| UNSPECIFIED | 9 | Extension information of the unspecified type.< | diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 9e4324677a..430e3a52ac 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -23,10 +23,10 @@ Starts an ability. This method uses a callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------------------- | ---- | ------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -62,9 +62,9 @@ Starts an ability. This method uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | --------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| **Example** @@ -100,14 +100,14 @@ Obtains a **dataAbilityHelper** object. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | ------------------------ | -| uri | string | Yes | URI of the file to open.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| uri | string | Yes | URI of the file to open.| **Return value** -| Type | Description | -| ----------------- | -------------------------------------------- | +| Type | Description | +| ----------------- | ------------------------------- | | DataAbilityHelper | A utility class used to help other abilities access the Data ability.| **Example** @@ -129,10 +129,10 @@ Starts an ability. This method uses a callback to return the execution result wh **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | --------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | **Example** @@ -166,14 +166,14 @@ Starts an ability. This method uses a promise to return the execution result whe **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | ------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| **Return value** -| Type | Description | -| ----------------------------------------- | -------------- | +| Type | Description | +| ---------------------------------------- | ------- | | Promise\<[AbilityResult](#abilityresult)> | Promised returned with the execution result.| **Example** @@ -222,10 +222,10 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------- | ---- | ------------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | -------------- | +| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -270,14 +270,14 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------- | ---- | ------------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------------- | +| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------- | | Promise\ | Promise used to return the result.| **Example** @@ -327,9 +327,9 @@ Checks whether the main window of this ability has the focus. This method uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| **Example** @@ -350,8 +350,8 @@ Checks whether the main window of this ability has the focus. This method uses a **Return value** -| Type | Description | -| ----------------- | ---------------------------------------------------------- | +| Type | Description | +| ----------------- | ------------------------------------- | | Promise\ | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| **Example** @@ -375,9 +375,9 @@ Obtains the **Want** object sent from this ability. This method uses a callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ------------------ | -| callback | AsyncCallback\<[Want](#want)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------- | ---- | --------- | +| callback | AsyncCallback\<[Want](#want)> | Yes | Callback used to return the result.| **Example** @@ -398,8 +398,8 @@ Obtains the **Want** object sent from this ability. This method uses a promise t **Return value** -| Type | Description | -| ----------------------- | ------------------------- | +| Type | Description | +| ----------------------- | ---------------- | | Promise\<[Want](#want)> | Promise used to return the result.| **Example** @@ -421,8 +421,8 @@ Obtains the application context. **Return value** -| Type | Description | -| ------- | -------------------- | +| Type | Description | +| ------- | ---------- | | Context | Application context returned.| **Example** @@ -445,9 +445,9 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | -------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -468,8 +468,8 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Return value** -| Type | Description | -| -------------- | ------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result.| **Example** @@ -490,35 +490,35 @@ Connects this ability to a specific Service ability. This method uses a callback **Parameters** -| Name | Type | Mandatory| Description | -| ------- | -------------- | ---- | ---------------------------- | -| request | [Want](#want) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------- | -------------- | ---- | --------------------- | +| request | [Want](#want) | Yes | Service ability to connect.| +| options | ConnectOptions | Yes | Callback used to return the result. | Want **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable | Type | Mandatory| Description | -| ------------ | -------- | -------- | ---- | ---------------------------------- | -| deviceId | Read-only | string | No | Device ID of the Service ability to connect. The default value is the local device ID.| -| bundleName | Read-only | string | Yes | Bundle name of the Service ability to connect. | -| abilityName | Read-only | string | Yes | Class name of the Service ability to connect. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ---------------------------------------- | +| deviceId | Read-only | string | No | Device ID of the Service ability to connect. The default value is the local device ID.| +| bundleName | Read-only | string | Yes | Bundle name of the Service ability to connect. | +| abilityName | Read-only | string | Yes | Class name of the Service ability to connect. | ConnectOptions **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------ | -------- | -------- | ---- | ---------------------------------- | -| onConnect | Read-only | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | Read-only | function | Yes | Callback invoked when the connection fails. | -| onFailed | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------ | ---- | -------- | ---- | ------------------------- | +| onConnect | Read-only | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect | Read-only | function | Yes | Callback invoked when the connection fails. | +| onFailed | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ------ | -------------------- | | number | Returns the ID of the Service ability connected.| **Example** @@ -559,10 +559,10 @@ Disconnects this ability from a specific Service ability. This method uses a cal **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------- | ---- | ------------------------------ | -| connection | number | Yes | ID of the Service ability to disconnect.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | -------------------- | ---- | ----------------------- | +| connection | number | Yes | ID of the Service ability to disconnect.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -606,14 +606,14 @@ Disconnects this ability from a specific Service ability. This method uses a pro **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------------------ | -| connection | number | Yes | ID of the Service ability to disconnect.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ----------------------- | +| connection | number | Yes | ID of the Service ability to disconnect.| **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------- | | Promise\ | Promise used to return the result.| **Example** @@ -658,16 +658,14 @@ Obtains the window corresponding to this ability. This method uses a callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the window.| **Example** ```javascript -GetWindow(){ - featureAbility.getWindow() - } +featureAbility.getWindow() ``` ## featureAbility.getWindow7+ @@ -680,20 +678,148 @@ Obtains the window corresponding to this ability. This method uses a promise to **Return value** -| Type | Description | -| ----------------- | ---------------------------------------------------------- | +| Type | Description | +| ----------------------- | ----------------------------- | | Promise\ | Promise used to return the window.| **Example** ```javascript -GetWindowPromise(){ - featureAbility.getWindow().then((data) => { - console.info("=============getWindowPromise========== " + JSON.stringify(data)); - }); - } +featureAbility.getWindow().then((data) => { + console.info("=============getWindowPromise========== " + JSON.stringify(data)); +}); +``` + +## ConnectOptions.onConnect7+ + +onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void; + +Callback invoked when the connection is successful. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ----------------- | ---- | -------- | +| elementName | ElementName | Yes | Element name. | +| remote | rpc.IRemoteObject | Yes | RPC remote object.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +## ConnectOptions.onDisconnect7+ + +onDisconnect(elementName: ElementName): void; + +Callback invoked when the connection fails. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ----------- | ---- | ---- | +| elementName | ElementName | Yes | Element name.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); ``` +## ConnectOptions.onFailed7+ + +onFailed(code: number): void; + +Callback invoked when **connectAbility** fails to be called. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| code | number | Yes | Number type.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + + + + ## AbilityWindowConfiguration @@ -705,13 +831,15 @@ The value is obtained through the **featureAbility.AbilityWindowConfiguration** featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED ``` -| Name | Name| Description | -| --------------------------- | ---- | ---------- | -| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Name | Description | +| ---------------------------------------- | ---- | ---------------------------------------- | +| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.| +| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode. | +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.| ## AbilityStartSetting @@ -726,34 +854,40 @@ The value is obtained through the **featureAbility.AbilityStartSetting** API. featureAbility.AbilityStartSetting.BOUNDS_KEY ``` -| Name | Name | Description | -| --------------- | --------------- | -------------------------- | -| BOUNDS_KEY7+ | "abilityBounds" | Ability window size.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_KEY7+ | "windowMode" | Ability window display mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| DISPLAY_ID_KEY7+ | "displayId" | Display device ID.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Name | Description | +| ---------------------------- | --------------- | ---------------------------------------- | +| BOUNDS_KEY7+ | "abilityBounds" | Ability window size.| +| WINDOW_MODE_KEY7+ | "windowMode" | Ability window display mode.| +| DISPLAY_ID_KEY7+ | "displayId" | Display device ID.| ## ErrorCode Enumerates error codes. -| Variable | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| NO_ERROR7+ | 0 | No error occurs.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| INVALID_PARAMETER7+ | -1 | Invalid parameter.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| ABILITY_NOT_FOUND7+ | -2 | The ability is not found.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| PERMISSION_DENY7+ | -3 | The request is denied.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Variable | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| NO_ERROR7+ | 0 | No error occurs.| +| INVALID_PARAMETER7+ | -1 | Invalid parameter.| +| ABILITY_NOT_FOUND7+ | -2 | The ability is not found.| +| PERMISSION_DENY7+ | -3 | The request is denied.| ## DataAbilityOperationType Enumerates operation types of the Data ability. -| Variable | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| TYPE_INSERT7+ | 1 | Insert operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_UPDATE7+ | 2 | Update operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_DELETE7+ | 3 | Deletion operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_ASSERT7+ | 4 | Assert operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Variable | Value | Description | +| ------------------------ | ---- | ---------------------------------------- | +| TYPE_INSERT7+ | 1 | Insert operation.| +| TYPE_UPDATE7+ | 2 | Update operation.| +| TYPE_DELETE7+ | 3 | Deletion operation.| +| TYPE_ASSERT7+ | 4 | Assert operation.| @@ -761,56 +895,56 @@ Enumerates operation types of the Data ability. **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| resultCode7+ | Read-only | number | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| -| want7+ | Read-only | [Want](#want) | No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------------------- | ---- | ------------- | ---- | ------------------------------------- | +| resultCode7+ | Read-only | number | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| +| want7+ | Read-only | [Want](#want) | No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | ## StartAbilityParameter **System capability**: SystemCapability.AbilityRuntime.FAModel -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| want | Read-only | [Want](#want) | Yes | Information about the ability to start. | -| abilityStartSetting | Read-only | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------------- | ---- | -------------------- | ---- | -------------------------------------- | +| want | Read-only | [Want](#want) | Yes | Information about the ability to start. | +| abilityStartSetting | Read-only | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| ## Want **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId8+ | Read-only | string | No | ID of the device that runs the ability. | -| bundleName8+ | Read-only | string | No | Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| -| abilityName8+ | Read-only | string | No | Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| -| uri8+ | Read-only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type8+ | Read-only | string | No | MIME type, for example, text/plain or image/*. | -| flags8+ | Read-only | number | No | How the **Want** object will be handled. By default, a number is passed. For details, see [flags](#flags).| -| action8+ | Read-only | string | No | Action option. | -| parameters8+ | Read-only | {[key: string]: any} | No | List of parameters in a **Want** object. | -| entities8+ | Read-only | Array\ | No | List of entities. | +| Name | Readable/Writable| Type | Mandatory| Description | +| -------------------------------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read-only | string | No | ID of the device that runs the ability. | +| bundleName | Read-only | string | No | Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read-only | string | No | Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| uri | Read-only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | Read-only | string | No | MIME type, for example, text/plain or image/*. | +| flags | Read-only | number | No | How the **Want** object will be handled. By default, a number is passed. For details, see [flags](#flags).| +| action | Read-only | string | No | Action option. | +| parameters | Read-only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read-only | Array\ | No | List of entities. | ## flags **System capability**: SystemCapability.Ability.AbilityBase -| Name | Name | Description | -| ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | -| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | -| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | -| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | -| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object passed to **ohos.app.Context#startAbility** and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | +| Name | Name | Description | +| ------------------------------------ | ---------- | ---------------------------------------- | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 67e1d8d19e..f574cc1589 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -45,13 +45,13 @@ Asynchronously obtains file information. This method uses a promise to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| - Example @@ -73,10 +73,10 @@ Asynchronously obtains file information. This method uses a callback to return t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked to return the file information obtained.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| - Example ```js @@ -95,14 +95,14 @@ Synchronously obtains file information. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | File information obtained.| - Example @@ -121,13 +121,13 @@ Asynchronously opens a directory. This method uses a promise to return the resul **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------- | + | path | string | Yes | Absolute path of the directory to open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------- | -------- | | Promise<[Dir](#dir)> | A **Dir** instance corresponding to the directory.| - Example @@ -149,10 +149,10 @@ Asynchronously opens a directory. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| - | callback | AsyncCallback<[Dir](#dir)> | Yes| Callback invoked when the directory is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | -------------------------------- | ---- | -------------- | + | path | string | Yes | Absolute path of the directory to open. | + | callback | AsyncCallback<[Dir](#dir)> | Yes | Callback invoked when the directory is open asynchronously.| - Example ```js @@ -173,13 +173,13 @@ Synchronously opens a directory. - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------- | + | path | string | Yes | Absolute path of the directory to open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ----------- | -------- | | [Dir](#dir) | A **Dir** instance corresponding to the directory.| - Example @@ -199,14 +199,14 @@ Asynchronously checks whether the current process can access a file. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -228,11 +228,11 @@ Asynchronously checks whether the current process can access a file. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is asynchronously checked.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously checked. | - Example ```js @@ -251,10 +251,10 @@ Synchronously checks whether the current process can access the specified file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - Example ```js @@ -275,13 +275,13 @@ Asynchronously closes a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -304,10 +304,10 @@ Asynchronously closes a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| - Example ```js @@ -327,9 +327,9 @@ Synchronously closes a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| - Example ```js @@ -346,8 +346,8 @@ Asynchronously closes the stream. This method uses a promise to return the resul **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -369,9 +369,9 @@ Asynchronously closes the stream. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback invoked when the stream is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| - Example ```js @@ -390,15 +390,15 @@ Asynchronously copies a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -420,12 +420,12 @@ Asynchronously copies a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is copied asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | - Example ```js @@ -444,11 +444,11 @@ Synchronously copies a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - Example ```js @@ -465,14 +465,14 @@ Asynchronously creates a directory. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -494,11 +494,11 @@ Asynchronously creates a directory. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the directory is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | - Example ```js @@ -519,10 +519,10 @@ Synchronously creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -539,15 +539,15 @@ Asynchronously opens a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | No| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | No| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ----- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | ----------- | | Promise<number> | File descriptor of the file opened.| - Example @@ -569,12 +569,12 @@ Asynchronously opens a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | Yes| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | Yes | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | - Example ```js @@ -593,15 +593,15 @@ Synchronously opens a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | No| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | No| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| + | Name | Type | Mandatory | Description | + | ----- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------- | | number | File descriptor of the file opened.| - Example @@ -623,15 +623,15 @@ Asynchronously reads data from a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------------- | ------ | | Promise<[ReadOut](#readout)> | Data read.| - Example @@ -659,12 +659,12 @@ Asynchronously reads data from a file. This method uses a callback to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes| Callback invoked when the data is read asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | - Example ```js @@ -691,15 +691,15 @@ Synchronously reads data from a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------- | | number | Length of the data read.| - Example @@ -719,13 +719,13 @@ Asynchronously deletes a directory. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the directory to delete.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -747,10 +747,10 @@ Asynchronously deletes a directory. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the directory is deleted asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | path | string | Yes | Absolute path of the directory to delete. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously.| - Example ```js @@ -769,9 +769,9 @@ Synchronously deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the directory to delete.| - Example ```js @@ -788,13 +788,13 @@ Asynchronously deletes a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the file to delete.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -816,10 +816,10 @@ Asynchronously deletes a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is deleted asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | path | string | Yes | Absolute path of the file to delete. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously.| - Example ```js @@ -840,9 +840,9 @@ Synchronously deletes a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the file to delete.| - Example ```js @@ -864,15 +864,15 @@ Asynchronously writes data into a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | -------- | | Promise<number> | Length of the data written in the file.| - Example @@ -900,12 +900,12 @@ Asynchronously writes data into a file. This method uses a callback to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - | callback | AsyncCallback<number> | Yes| Callback invoked when the data is written asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | - Example ```js @@ -932,15 +932,15 @@ Synchronously writes data into a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------- | | number | Length of the data written in the file.| - Example @@ -959,14 +959,14 @@ Asynchronously calculates the hash value of a file. This method uses a promise t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | algorithm | string | Yes| Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| + | Name | Type | Mandatory | Description | + | --------- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | -------------------------- | | Promise<string> | Promise used to return the hash value of the file. The hash value is a hexadecimal string consisting of digits and uppercase letters.| - Example @@ -988,11 +988,11 @@ Asynchronously calculates the hash value of a file. This method uses a callback **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | algorithm | string | Yes| Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| - | callback | AsyncCallback<string> | Yes| Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + | Name | Type | Mandatory | Description | + | --------- | --------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| + | callback | AsyncCallback<string> | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| - Example ```js @@ -1013,14 +1013,14 @@ Asynchronously changes the file permissions based on its path. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1042,11 +1042,11 @@ Asynchronously changes the file permissions based on its path. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file permissions are changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | - Example ```js @@ -1065,10 +1065,10 @@ Synchronously changes the file permissions based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -1085,12 +1085,12 @@ Asynchronously obtains file status information based on the file descriptor. Thi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| - Return value - | Type| Description| + | Type | Description | | -------- | -------- | | Promise<[Stat](#stat)> | Promise used to return the file status information obtained.| @@ -1113,10 +1113,10 @@ Asynchronously obtains file status information based on the file descriptor. Thi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked when the file status information is obtained asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | ---------------- | + | fd | number | Yes | File descriptor of the target file. | + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked when the file status information is obtained asynchronously.| - Example ```js @@ -1136,13 +1136,13 @@ Synchronously obtains file status information based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | File status information obtained.| - Example @@ -1161,14 +1161,14 @@ Asynchronously truncates a file based on the file descriptor. This method uses a **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1191,11 +1191,11 @@ Asynchronously truncates a file based on the file descriptor. This method uses a **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is truncated asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | - Example ```js @@ -1214,10 +1214,10 @@ Synchronously truncates a file based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | No| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| - Example ```js @@ -1234,14 +1234,14 @@ Asynchronously truncates a file based on its path. This method uses a promise to **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1263,11 +1263,11 @@ Asynchronously truncates a file based on its path. This method uses a callback t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is truncated asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | - Example ```js @@ -1286,10 +1286,10 @@ Synchronously truncates a file based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | No| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| - Example ```js @@ -1310,14 +1310,14 @@ Asynchronously reads the text of a file. This method uses a promise to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | -------- | ------ | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | ---------- | | Promise<string> | Promise used to return the content of the file read.| - Example @@ -1343,11 +1343,11 @@ Asynchronously reads the text of a file. This method uses a callback to return t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - | callback | AsyncCallback<string> | Yes| Callback invoked when the file is read asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<string> | Yes | Callback invoked when the file is read asynchronously. | - Example ```js @@ -1370,15 +1370,15 @@ Synchronously reads the text of a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | -------- | ------ | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | - | <string>| Content of the file read.| + | Type | Description | + | ------ | -------------------- | + | string | Content of the file read.| - Example ```js @@ -1395,13 +1395,13 @@ Asynchronously obtains link status information. This method uses a promise to re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the link status obtained.| - Example @@ -1423,10 +1423,10 @@ Asynchronously obtains link status information. This method uses a callback to r **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked when the link status information is obtained asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked when the link status information is obtained asynchronously. | - Example ```js @@ -1445,13 +1445,13 @@ Synchronously obtains link status information. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | Link status obtained.| - Example @@ -1473,14 +1473,14 @@ Asynchronously reads data from a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------------- | ------ | | Promise<[ReadOut](#readout)> | Data read.| - Example @@ -1506,11 +1506,11 @@ Asynchronously reads data from a file. This method uses a callback to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes| Callback invoked when the data is read asynchronously from the file.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously from the file. | - Example ```js @@ -1532,19 +1532,19 @@ Asynchronously renames a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldPath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------ | + | oldPath | string | Yes | Absolute path of the file to rename.| + | newPath | String | Yes | Absolute path of the file renamed. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example ```js - fileio.rename(oldPath, Newpath).then(function() { + fileio.rename(oldPath, newPath).then(function() { console.info("rename successfully"); }).catch(function(err){ console.info("rename failed with error:"+ err); @@ -1561,15 +1561,15 @@ Asynchronously renames a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldpath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| - | Callback | AsyncCallback<void> | Yes| Callback invoked when the file is asynchronously renamed.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | oldPath | string | Yes | Absolute path of the file to rename. | + | newPath | String | Yes | Absolute path of the file renamed. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed.| - Example ```js - fileio.rename(oldpath, Newpath, function(err){ + fileio.rename(oldPath, newPath, function(err){ }); ``` @@ -1583,14 +1583,14 @@ Synchronously renames a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldPath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | oldPath | string | Yes | Absolute path of the file to rename.| + | newPath | String | Yes | Absolute path of the file renamed. | - Example ```js - fileio.renameSync(oldpath, newpath); + fileio.renameSync(oldPath, newPath); ``` @@ -1603,13 +1603,13 @@ Asynchronously synchronizes a file. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1631,10 +1631,10 @@ Asynchronously synchronizes a file. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| - | Callback | AsyncCallback<void> | Yes| Callback invoked when the file is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the file to synchronize. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is synchronized in asynchronous mode.| - Example ```js @@ -1653,9 +1653,9 @@ Synchronizes a file in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Example ```js @@ -1672,13 +1672,13 @@ Asynchronously synchronizes data in a file. This method uses a promise to return **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1700,10 +1700,10 @@ Asynchronously synchronizes data in a file. This method uses a callback to retur **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ----------------- | + | fd | number | Yes | File descriptor of the file to synchronize. | + | callback | AsyncCallback <void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| - Example ```js @@ -1722,9 +1722,9 @@ Synchronizes data in a file in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Example ```js @@ -1741,14 +1741,14 @@ Asynchronously creates a symbolic link based on a path. This method uses a promi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1770,11 +1770,11 @@ Asynchronously creates a symbolic link based on a path. This method uses a callb **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the symbolic link is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| - Example ```js @@ -1793,10 +1793,10 @@ Synchronously creates a symbolic link based on a specified path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link.| - Example ```js @@ -1813,15 +1813,15 @@ Asynchronously changes the file owner based on its path. This method uses a prom **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New user ID (UID).| - | gid | number | Yes| New group ID (GID).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New user ID (UID). | + | gid | number | Yes | New group ID (GID).| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1844,12 +1844,12 @@ Asynchronously changes the file owner based on its path. This method uses a call **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -1869,11 +1869,11 @@ Synchronously changes the file owner based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -1891,13 +1891,13 @@ Asynchronously creates a temporary directory. This method uses a promise to retu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | --------------------- | ---------- | | Promise<string> | Unique path generated.| - Example @@ -1919,10 +1919,10 @@ Asynchronously creates a temporary directory. This method uses a callback to ret **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| - | callback | AsyncCallback<string> | Yes| Callback invoked when a temporary directory is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | - Example ```js @@ -1941,13 +1941,13 @@ Synchronously creates a temporary directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------ | ---------- | | string | Unique path generated.| - Example @@ -1965,14 +1965,14 @@ Asynchronously changes the file permissions based on the file descriptor. This m **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1994,11 +1994,11 @@ Asynchronously changes the file permissions based on the file descriptor. This m **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file permissions are changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback <void> | Yes | Callback invoked when the file permissions are changed asynchronously. | - Example ```js @@ -2017,10 +2017,10 @@ Synchronously changes the file permissions based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -2037,14 +2037,14 @@ Asynchronously opens a stream based on the file path. This method uses a promise **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| - Example @@ -2066,11 +2066,11 @@ Asynchronously opens a stream based on the file path. This method uses a callbac **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - | callback | AsyncCallback<[Stream](#stream7)> | Yes| Callback invoked when the stream is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | callback | AsyncCallback<[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | - Example ```js @@ -2089,14 +2089,14 @@ Synchronously opens a stream based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| - Example @@ -2114,14 +2114,14 @@ Asynchronously opens a stream based on the file descriptor. This method uses a p **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| - Example @@ -2143,11 +2143,11 @@ Asynchronously opens a stream based on the file descriptor. This method uses a c **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - | callback | AsyncCallback <[Stream](#stream7)> | Yes| Callback invoked when the stream is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | callback | AsyncCallback <[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | - Example ```js @@ -2166,14 +2166,14 @@ Synchronously opens a stream based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| - Example @@ -2191,15 +2191,15 @@ Asynchronously changes the file owner based on the file descriptor. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -2222,12 +2222,12 @@ Asynchronously changes the file owner based on the file descriptor. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -2247,11 +2247,11 @@ Synchronously changes the file owner based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -2269,15 +2269,15 @@ Asynchronously changes the file owner based on the file path, changes the owner **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -2300,12 +2300,12 @@ Asynchronously changes the file owner based on the file path, changes the owner **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -2325,11 +2325,11 @@ Synchronously changes the file owner based on the file path and changes the owne **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -2347,15 +2347,15 @@ Asynchronously listens for the changes of a file or directory. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filename | string | Yes| Absolute path of the target file.| - | events | Number | Yes| - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| - | callback | AsyncCallback<number > | Yes| Called each time a change is detected.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------------- | ---- | ---------------------------------------- | + | filename | string | Yes | Absolute path of the target file. | + | events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| + | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | -------------------- | ---------- | | [Watcher](#watcher7) | Instance for listening for a file change event.| - Example @@ -2372,11 +2372,11 @@ Obtains the file read result. This class applies only to the **read()** method. **System capability**: SystemCapability.FileManagement.File.FileIO -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| bytesRead | number | Yes| Yes| Length of the data read.| -| offset | number | Yes| Yes| Position of the buffer to which the data will be read in reference to the start address of the buffer.| -| buffer | ArrayBufer | Yes| Yes| Buffer for storing the data read.| +| Name | Type | Readable | Writable | Description | +| --------- | ---------- | ---- | ---- | ----------------- | +| bytesRead | number | Yes | Yes | Length of the data read. | +| offset | number | Yes | Yes | Position of the buffer to which the data will be read in reference to the start address of the buffer.| +| buffer | ArrayBufer | Yes | Yes | Buffer for storing the data read. | ## Stat @@ -2387,20 +2387,20 @@ Provides detailed file information. Before calling a method of the **Stat** clas ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| dev | number | Yes| No| Major device number.| -| ino | number | Yes| No| File ID. Different files on the same device have different **ino**s.| -| mode | number | Yes| No| File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| -| nlink | number | Yes| No| Number of hard links in the file.| -| uid | number | Yes| No| User ID, that is ID of the file owner.| -| gid | number | Yes| No| Group ID, that is, ID of the user group of the file.| -| rdev | number | Yes| No| Minor device number.| -| size | number | Yes| No| File size, in bytes. This parameter is valid only for regular files.| -| blocks | number | Yes| No| Number of blocks occupied by a file. Each block is 512 bytes.| -| atime | number | Yes| No| Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| -| mtime | number | Yes| No| Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| -| ctime | number | Yes| No| Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| dev | number | Yes | No | Major device number. | +| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s. | +| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| nlink | number | Yes | No | Number of hard links in the file. | +| uid | number | Yes | No | User ID, that is ID of the file owner. | +| gid | number | Yes | No | Group ID, that is, ID of the user group of the file. | +| rdev | number | Yes | No | Minor device number. | +| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | +| blocks | number | Yes | No | Number of blocks occupied by a file. Each block is 512 bytes. | +| atime | number | Yes | No | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| mtime | number | Yes | No | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| ctime | number | Yes | No | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | ### isBlockDevice @@ -2412,8 +2412,8 @@ Checks whether the current directory entry is a block special file. A block spec **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ---------------- | | boolean | Whether the directory entry is a block special file.| - Example @@ -2431,8 +2431,8 @@ Checks whether the current directory entry is a character special file. A charac **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------- | | boolean | Whether the directory entry is a character special file.| - Example @@ -2450,8 +2450,8 @@ Checks whether a directory entry is a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ------------- | | boolean | Whether the directory entry is a directory.| - Example @@ -2469,8 +2469,8 @@ Checks whether the current directory entry is a named pipe (or FIFO). Named pipe **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------- | | boolean | Whether the directory entry is a FIFO.| - Example @@ -2488,8 +2488,8 @@ Checks whether a directory entry is a regular file. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------- | | boolean | Whether the directory entry is a regular file.| - Example @@ -2507,8 +2507,8 @@ Checks whether a directory entry is a socket. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------- | | boolean | Whether the directory entry is a socket.| - Example @@ -2526,8 +2526,8 @@ Checks whether a directory entry is a symbolic link. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------- | | boolean | Whether the directory entry is a symbolic link.| - Example @@ -2564,9 +2564,9 @@ Asynchronously stops **watcher**. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback invoked when **watcher** is stopped asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| - Example ```js @@ -2574,3 +2574,564 @@ Asynchronously stops **watcher**. This method uses a callback to return the resu // Do something. }); ``` + + +## Stream7+ + +File stream. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. + + +### close7+ + +close(): Promise<void> + +Asynchronously closes the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream close result.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.close().then(function(){ + console.info("close fileStream successfully"); + }).catch(function(err){ + console.info("close fileStream failed with error:"+ err); + }); + ``` + + +### close7+ + +close(callback: AsyncCallback<void>): void + +Asynchronously closes the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.close(function (err) { + // do something + }); + ``` + + +### closeSync + +closeSync(): void + +Synchronously closes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.closeSync(); + ``` + + +### flush7+ + +flush(): Promise<void> + +Asynchronously flushes the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream flushing result.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flush().then(function (){ + console.info("flush successfully"); + }).catch(function(err){ + console.info("flush failed with error:"+ err); + }); + ``` + + +### flush7+ + +flush(callback: AsyncCallback<void>): void + +Asynchronously flushes the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | -------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flush(function (err) { + // do something + }); + ``` + + +### flushSync7+ + +flushSync(): void + +Synchronously flushes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flushSync(); + ``` + + +### write7+ + +write(buffer: ArrayBuffer | string, options?: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}): Promise<number> + +Asynchronously writes data into the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + +- Return value + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Length of the data written in the file.| + +- Example + ```js + let ss= fileio.createStreamSync(fpath, "r+"); + ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ + console.info("write successfully:"+ number); + }).catch(function(err){ + console.info("write failed with error:"+ err); + }); + ``` + + +### write7+ + +write(buffer: ArrayBuffer | string, options: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}, callback: AsyncCallback<number>): void + +Asynchronously writes data into the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +- Example + ```js + let ss= fileio.createStreamSync(fpath, "r+"); + ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { + if (!err) { + // do something + console.log(bytesWritten); + } + }); + ``` + + +### writeSync7+ + +writeSync(buffer: ArrayBuffer | string, options?: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}): number + +Synchronously writes data into the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + +- Return value + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| + +- Example + ```js + let ss= fileio.createStreamSync(fpath,"r+"); + let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); + ``` + + +### read7+ + +read(buffer: ArrayBuffer, options?: { + position?: number; + offset?: number; + length?: number; +}): Promise<ReadOut> + +Asynchronously reads data from the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + +- Return value + | Type | Description | + | ---------------------------------- | ------ | + | Promise<[ReadOut](#readout)> | Data read.| + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ + console.info("read data successfully"); + }).catch(function(err){ + console.info("read data failed with error:"+ err); + }); + ``` + + +### read7+ + +read(buffer: ArrayBuffer, options: { + position?: number; + offset?: number; + length?: number; +}, callback: AsyncCallback<ReadOut>): void + +Asynchronously reads data from the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { + if (!err) { + // do something + } + }); + ``` + + +### readSync7+ + +readSync(buffer: ArrayBuffer, options?: { + position?: number; + offset?: number; + length?: number; +}): number + +Synchronously reads data from the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + +- Return value + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); + ``` + + +## Dir + +Manages directories. Before calling a method of the **Dir** class, use the [opendir()](#fileioopendir) method synchronously or asynchronously to create a **Dir** instance. + + +### read + +read(): Promise<Dirent> + +Asynchronously reads the next directory entry. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | -------------------------------- | ------------- | + | Promise<[Dirent](#dirent)> | Directory entry that is read asynchronously.| + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.read().then(function (dirent){ + console.info("read successfully:"+ dirent.name); + }).catch(function(err){ + console.info("read failed with error:"+ err); + }); + ``` + + +### read + +read(callback: AsyncCallback<Dirent>): void + +Asynchronously reads the next directory entry. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | -------------------------------------- | ---- | ---------------- | + | callback | AsyncCallback<[Dirent](#dirent)> | Yes | Callback invoked when the next directory entry is asynchronously read.| + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.read(function (err, dirent) { + if (!err) { + // do something + console.log(dirent.name) + } + }); + ``` + + +### readSync + +readSync(): Dirent + +Synchronously reads the next directory entry. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ----------------- | -------- | + | [Dirent](#dirent) | Directory entry read.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let dirent = dir.readSync(); + ``` + + +### closeSync + +closeSync(): void + +Closes a directory. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.closeSync(); + ``` + + +## Dirent + +Provides information about files and directories. Before calling a method of the **Dirent** class, use the [dir.read()](#read) method synchronously or asynchronously to create a **Dirent** instance. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------- | +| name | string | Yes | No | Directory entry name.| + + +### isBlockDevice + +isBlockDevice(): boolean + +Checks whether the current directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the directory entry is a block special file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isBLockDevice = dir.readSync().isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice(): boolean + +Checks whether a directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the directory entry is a character special file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isCharacterDevice = dir.readSync().isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory(): boolean + +Checks whether a directory entry is a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ------------- | + | boolean | Whether the directory entry is a directory.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isDirectory = dir.readSync().isDirectory(); + ``` + + +### isFIFO + +isFIFO(): boolean + +Checks whether the current directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a FIFO.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isFIFO = dir.readSync().isFIFO(); + ``` + + +### isFile + +isFile(): boolean + +Checks whether a directory entry is a regular file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a regular file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isFile = dir.readSync().isFile(); + ``` + + +### isSocket + +isSocket(): boolean + +Checks whether a directory entry is a socket. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | -------------- | + | boolean | Whether the directory entry is a socket.| + +- Example + ```js + let dir = fileio.opendirSync(dpath); + let isSocket = dir.readSync().isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink(): boolean + +Checks whether a directory entry is a symbolic link. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a symbolic link.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isSymbolicLink = dir.readSync().isSymbolicLink(); + ``` diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index 18891f758a..c3b738b12c 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -2,7 +2,7 @@ >![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > >- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- This is a system API and cannot be called by third-party applications. Currently, it can be called only by **filepicker**. +>- 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 diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md new file mode 100644 index 0000000000..1091770862 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formInfo.md @@ -0,0 +1,116 @@ +# FormInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +Provides widget information. + +## Modules to Import + +``` +import formInfo from '@ohos.application.formInfo'; +``` + +## Required Permissions + +None. + +## FormInfo + +Describes widget information. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Readable/Writable| Type | Description | +| ----------- | -------- | -------------------- | ------------------------------------------------------------ | +| bundleName | Read only | string | Name of the bundle to which the widget belongs. | +| moduleName | Read only | string | Name of the module to which the widget belongs. | +| abilityName | Read only | string | Name of the ability to which the widget belongs. | +| name | Read only | string | Widget name. | +| description | Read only | string | Description of the widget. | +| type | Read only | [FormType](#formtype) | Widget type. Currently, only JS widgets are supported.| +| jsComponentName | Read only | string | Component name of the JS widget. | +| colorMode | Read only | [ColorMode](#colormode) | Color mode of the widget. | +| isDefault | Read only | boolean | Whether the widget is the default one. | +| updateEnabled | Read only | boolean | Whether the widget is updatable. | +| formVisibleNotify | Read only | string | Whether to send a notification when the widget is visible. | +| relatedBundleName | Read only | string | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | Read only | string | Time when the widget was updated. | +| formConfigAbility | Read only | string | Configuration ability of the widget. | +| updateDuration | Read only | string | Widget update period.| +| defaultDimension | Read only | number | Default dimension of the widget. | +| supportDimensions | Read only | Array<number> | Dimensions supported by the widget. | +| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Automatic mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Readable/Writable| Type | Description | +| ----------- | -------- | -------------------- | ------------------------------------------------------------ | +| formState | Read only | [FormState](#formstate) | Widget state. | +| want | Read only | Want | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md index 54470f5231..5f92677ec4 100644 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ b/en/application-dev/reference/apis/js-apis-formbindingdata.md @@ -25,7 +25,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object or string| No | Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| +| obj | Object or string| No | Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| **Return value** @@ -38,20 +38,20 @@ Creates a **FormBindingData** object. **Example** ```js - let obj = {"temperature": "21°"}; + let fd = fileio.openSync(path); + let obj = { + "temperature": "21°", + "formImages": {"image": fd} + }; let formBindingDataObj = formBindingData.createFormBindingData(obj); ``` -## formBindingData.FormBindingData - -data: Object +## Attributes Describes a **FormBindingData** object. **System capability**: SystemCapability.Ability.Form -**Parameters** - -| Name| Type | Description | -| ---- | -------------- | ------------------------------------------------------------ | -| data | Object or string| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| +| Name| Readable| Writable| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | -------- | +| data | Yes| No| Object | Yes| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-formerror.md new file mode 100644 index 0000000000..37eecd8530 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formerror.md @@ -0,0 +1,49 @@ +# FormError + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +Provides widget-related error codes. + +## Modules to Import + +``` +import formError from '@ohos.application.formError'; +``` + +## Required Permissions + +None. + +## enum FormError + +Enumerates the available error codes. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| ERR_COMMON | 1 | Default error code. | +| ERR_PERMISSION_DENY | 2 | No permission to perform the operation. | +| ERR_GET_INFO_FAILED | 4 | Failed to query widget information. | +| ERR_GET_BUNDLE_FAILED | 5 | Failed to query the bundle information. | +| ERR_GET_LAYOUT_FAILED | 6 | Failed to query the layout information. | +| ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. | +| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match. | +| ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. | +| ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. | +| ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. | +| ERR_MAX_INSTANCES_PER_FORM | 12 | The number of instances per widget exceeds the upper limit. | +| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets applied by other applications. | +| ERR_PROVIDER_DEL_FAIL | 14 | The widget provider failed to delete the widget. | +| ERR_MAX_FORMS_PER_CLIENT | 15 | The number of widgets applied for by the widget host exceeds the upper limit. | +| ERR_MAX_SYSTEM_TEMP_FORMS | 16 | The number of temporary widgets exceeds the upper limit. | +| ERR_FORM_NO_SUCH_MODULE | 17 | The module does not exist. | +| ERR_FORM_NO_SUCH_ABILITY | 18 | The ability component does not exist. | +| ERR_FORM_NO_SUCH_DIMENSION | 19 | The widget dimension does not exist. | +| ERR_FORM_FA_NOT_INSTALLED | 20 | The FA where the widget is located is not installed. | +| ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. | +| ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | +| ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md deleted file mode 100644 index a96feb9ef2..0000000000 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ /dev/null @@ -1,219 +0,0 @@ -# FormExtension - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - -Provides **FormExtension** APIs. - -## Modules to Import - -``` -import FormExtension from '@ohos.application.FormExtension'; -``` - -## Required Permissions - -None - -## Attributes - -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This class is inherited from **ExtensionContext**.
**System capability**: SystemCapability.Ability.Form| - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -Called to notify the widget provider that a **Form** instance (widget) has been created. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | - | want | [Want](js-apis-featureAbility.md#want) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } - } - ``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -Called to notify the widget provider that a temporary widget has been converted to a normal one. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| - -**Example** - - ``` - export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } - } - ``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-formextensioncontext.md) class to update the widget data. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - ``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -Called to notify the widget provider of the change of visibility. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | --------- | ------------------------- | ---- | ---------------------------- | - | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - } - ``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -Called to instruct the widget provider to receive and process the widget event. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ---------------------- | - | formId | string | Yes | ID of the widget that requests the event.| - | message | string | Yes | Event message. | - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } - } - ``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -Called to notify the widget provider that a **Form** instance (widget) has been destroyed. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget to be destroyed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } - } - ``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](#section188911144124715) | Yes| New configuration.| - -**Example** - - ```js - class MyFormExtension extends MyFormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md new file mode 100644 index 0000000000..0cf54af57b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -0,0 +1,1010 @@ +# FormHost + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +Provides APIs related to the widget host. + +## Modules to Import + +``` +import formHost from '@ohos.application.formHost'; +``` + +## Required Permissions + +ohos.permission.REQUIRE_FORM + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void; + +Deletes a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.deleteForm(formId, (error, data) => { + if (error) { + console.log('formHost deleteForm, error:' + error.code); + } + }); + ``` + +## deleteForm + +deleteForm(formId: string): Promise<void>; + +Deletes a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Parameters** + + ```js + var formId = "12400633174999288"; + formHost.deleteForm(formId).catch((error) => { + console.log('formProvider deleteForm, error:' + JSON.stringify(error)); + }); + ``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void; + +Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + error.code); + } + }); + ``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void; + +Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and determines whether to retain the cache information based on the setting. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ----------- | + | formId | string | Yes | ID of a widget. | + | isReleaseCache | boolean | Yes | Whether to release the cache.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + error.code); + } + }); + ``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void>; + +Releases a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and determines whether to retain the cache information based on the setting. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ----------- | + | formId | string | Yes | ID of a widget. | + | isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, true).catch((error) => { + console.log('formProvider releaseForm, error:' + JSON.stringify(error)); + }); + ``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void; + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.requestForm(formId, (error, data) => { + if (error) { + console.log('formHost requestForm, error:' + error.code); + } + }); + ``` + +## requestForm + +requestForm(formId: string): Promise<void>; + +Requests a widget update. This API uses a promise to return the result. + +**System capability** + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.requestForm(formId).catch((error) => { + console.log('formProvider requestForm, error:' + JSON.stringify(error)); + }); + ``` + +## castTempForm + +castTempForm(formId: string, callback: AsyncCallback<void>): void; + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.castTempForm(formId, (error, data) => { + if (error) { + console.log('formHost castTempForm, error:' + error.code); + } + }); + ``` + +## castTempForm + +castTempForm(formId: string): Promise<void>; + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.castTempForm(formId).catch((error) => { + console.log('formProvider castTempForm, error:' + JSON.stringify(error)); + }); + ``` + +## notifyVisibleForms + +notifyVisibleForms(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget visible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyVisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyVisibleForms, error:' + error.code); + } + }); + ``` + +## notifyVisibleForms + +notifyVisibleForms(formId: string): Promise<void>; + +Instructs the widget framework to make a widget visible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyVisibleForms(formId).catch((error) => { + console.log('formProvider notifyVisibleForms, error:' + JSON.stringify(error)); + }); + ``` + +## notifyInvisibleForms + +notifyInvisibleForms(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget invisible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyInvisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyInvisibleForms, error:' + error.code); + } + }); + ``` + +## notifyInvisibleForms + +notifyInvisibleForms(formId: string): Promise<void>; + +Instructs the widget framework to make a widget invisible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyInvisibleForms(formId).catch((error) => { + console.log('formProvider notifyInvisibleForms, error:' + JSON.stringify(error)); + }); + ``` + +## enableFormsUpdate + +enableFormsUpdate(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget to be updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.enableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost enableFormsUpdate, error:' + error.code); + } + }); + ``` + +## enableFormsUpdate + +enableFormsUpdate(formId: string): Promise<void>; + +Instructs the widget framework to make a widget to be updatable. This API uses a promise to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.enableFormsUpdate(formId).catch((error) => { + console.log('formProvider enableFormsUpdate, error:' + JSON.stringify(error)); + }); + ``` + +## disableFormsUpdate + +disableFormsUpdate(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget not to be updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the disabled state and cannot receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.disableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost disableFormsUpdate, error:' + error.code); + } + }); + ``` + +## disableFormsUpdate + +disableFormsUpdate(formId: string): Promise<void>; + +Instructs the widget framework to make a widget not to be updatable. This API uses a promise to return the result. After this API is called, the widget is in the disabled state and cannot receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.disableFormsUpdate(formId).catch((error) => { + console.log('formProvider disableFormsUpdate, error:' + JSON.stringify(error)); + }); + ``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void; + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.isSystemReady((error, data) => { + if (error) { + console.log('formHost isSystemReady, error:' + error.code); + } + }); + ``` + +## isSystemReady + +isSystemReady(): Promise<void>; + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.isSystemReady().catch((error) => { + console.log('formProvider isSystemReady, error:' + JSON.stringify(error)); + }); + ``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo((error, data) => { + if (error) { + console.log('formHost getAllFormsInfo, error:' + error.code); + } + }); + ``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<FormInfo>>; + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo().catch((error) => { + console.log('formProvider getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getFormsInfo("com.example.ohos.accountjsdemo", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + error.code); + } + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | moduleName | string | Yes| Module name.| + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getFormsInfo("com.example.ohos.accountjsdemo", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + error.code); + } + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<FormInfo>>; + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo().catch((error) => { + console.log('formProvider getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void; + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | callback | AsyncCallback<number> | Yes| Callback used to return the number of widgets deleted.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds, (error, data) => { + if (error) { + console.log('formHost deleteInvalidForms, error:' + error.code); + } + }); + ``` + +## deleteInvalidForms + +function deleteInvalidForms(formIds: Array<string>): Promise<number>; + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds).catch((error) => { + console.log('formProvider deleteInvalidForms, error:' + JSON.stringify(error)); + }); + ``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<FormStateInfo>): void; + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-featureAbility.md#want) | Yes | **Want** information carried to query the widget state.| +| callback | AsyncCallback<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Yes| Callback used to return the widget state.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + formHost.acquireFormState(want, (error, data) => { + if (error) { + console.log('formHost acquireFormState, error:' + error.code); + } + }); + ``` + +## acquireFormState + +function acquireFormState(want: Want): Promise<FormStateInfo>; + +Obtains the widget state. This API uses a promise to return the result. + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Promise used to return the widget state.| + +**System capability**: + +SystemCapability.Ability.Form + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + formHost.acquireFormState(want).catch((error) => { + console.log('formProvider acquireFormState, error:' + JSON.stringify(error)); + }); + ``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void; + +Subscribes to widget uninstall events. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| + | callback | Callback<string> | Yes| Callback used to return the result.| + +**Example** + + ```js + formHost.on("formUninstall", (error, data) => { + if (error) { + console.log('formHost on formUninstall, error:' + error.code); + } + }); + ``` + +## off("formUninstall") + +off(type: "formUninstall", callback: Callback<string>): void; + +Unsubscribes from widget uninstall events. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | type | string | Yes | Type of event to unsubscribe from. The value **formUninstall** indicates a widget uninstallation event.| + | callback | Callback<string> | Yes| Callback used to return the result.| + +**Example** + + ```js + formHost.off("formUninstall", (error, data) => { + if (error) { + console.log('formHost off formUninstall, error:' + error.code); + } + }); + ``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void; + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isVisible | boolean | Yes | Whether to be visible.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsVisible(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsVisible, error:' + error.code); + } + }); + ``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void>; + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isVisible | boolean | Yes | Whether to be visible.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsVisible(formIds, true).catch((error) => { + console.log('formProvider notifyFormsVisible, error:' + JSON.stringify(error)); + }); + ``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void; + +Instructs the widgets to enable or disable update. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to enable update.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsEnableUpdate, error:' + error.code); + } + }); + ``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void>; + +Instructs the widgets to enable or disable update. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to enable update.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsEnableUpdate(formIds, true).catch((error) => { + console.log('formProvider notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index f682cbc36b..40367d50bc 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -61,6 +61,12 @@ SystemCapability.Ability.Form | formId | string | Yes | ID of a widget. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +**Return value** + + | Type | Description | + | ------------- | ---------------------------------- | + | Promise\ |Promise used to return the result. | + **Example** ```js @@ -118,6 +124,12 @@ SystemCapability.Ability.Form | formId | string | Yes | ID of the widget to update.| | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 2c6fbbdfac..7d4694bfa7 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,7 +1,7 @@ -# Geolocation - New +# Geolocation -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,26 +12,23 @@ import geolocation from '@ohos.geolocation'; ``` - -## Required Permissions - -ohos.permission.LOCATION - -ohos.permission.LOCATION_IN_BACKGROUND - - ## geolocation.on('locationChange') on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void Registers a listener for location changes with a location request initiated. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationChange** indicates a location change event. | - | request | LocationRequest | Yes | Location request. | - | callback | Callback<[Location](#location)> | Yes | Callback used to return the location change event. | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | request | LocationRequest | Yes| Location request.| + | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + - Example @@ -50,11 +47,16 @@ off(type: 'locationChange', callback?: Callback<Location>) : void Unregisters the listener for location changes with the corresponding location request deleted. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationChange** indicates a location change event. | - | callback | Callback<[Location](#location)> | No | Callback used to return the location change event. | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| + - Example @@ -74,11 +76,16 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void Registers a listener for location service status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationServiceState** indicates a location service status change event. | - | callback | Callback<boolean> | Yes | Callback used to return the location service status change event. | + | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| + | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| + - Example @@ -96,11 +103,16 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; Unregisters the listener for location service status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationServiceState** indicates a location service status change event. | - | callback | Callback<boolean> | No | Callback used to return the location service status change event. | + | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| + | callback | Callback<boolean> | No| Callback used to return the location service status change event.| + - Example @@ -113,18 +125,23 @@ Unregisters the listener for location service status change events. ``` -## geolocation.on('cachedGnssLocationsReporting') +## geolocation.on('cachedGnssLocationsReporting')8+ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; Registers a listener for cached GNSS location reports. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations. | - | request | CachedGnssLocationsRequest | Yes | Request for reporting cached GNSS location. | - | callback | Callback<boolean> | Yes | Callback used to return cached GNSS locations. | + | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| + | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| + | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + - Example @@ -137,17 +154,22 @@ Registers a listener for cached GNSS location reports. ``` -## geolocation.off('cachedGnssLocationsReporting') +## geolocation.off('cachedGnssLocationsReporting')8+ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; Unregisters the listener for cached GNSS location reports. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations. | - | callback | Callback<boolean> | No | Callback used to return cached GNSS locations. | + | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| + | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| + - Example @@ -161,17 +183,22 @@ Unregisters the listener for cached GNSS location reports. ``` -## geolocation.on('gnssStatusChange') +## geolocation.on('gnssStatusChange')8+ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; Registers a listener for GNSS satellite status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **gnssStatusChange** indicates a GNSS satellite status change. | - | callback | Callback<SatelliteStatusInfo> | Yes | Callback used to return GNSS satellite status changes. | + | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| + | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| + - Example @@ -183,17 +210,21 @@ Registers a listener for GNSS satellite status change events. ``` -## geolocation.off('gnssStatusChange') +## geolocation.off('gnssStatusChange')8+ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; Unregisters the listener for GNSS satellite status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **gnssStatusChange** indicates a GNSS satellite status change. | - | callback | Callback<SatelliteStatusInfo> | No | Callback used to return GNSS satellite status changes. | + | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| + | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| - Example @@ -206,17 +237,22 @@ Unregisters the listener for GNSS satellite status change events. ``` -## geolocation.on('nmeaMessageChange') +## geolocation.on('nmeaMessageChange')8+ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; Registers a listener for GNSS NMEA message change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change. | - | callback | Callback<string> | Yes | Callback used to return GNSS NMEA message changes. | + | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| + | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| + - Example @@ -228,17 +264,22 @@ Registers a listener for GNSS NMEA message change events. ``` -## geolocation.off('nmeaMessageChange') +## geolocation.off('nmeaMessageChange')8+ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; Unregisters the listener for GNSS NMEA message change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change. | - | callback | Callback<string> | No | Callback used to return GNSS NMEA message changes. | + | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| + | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| + - Example @@ -251,18 +292,23 @@ Unregisters the listener for GNSS NMEA message change events. ``` -## geolocation.on('fenceStatusChange') +## geolocation.on('fenceStatusChange')8+ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; Registers a listener for status change events of the specified geofence. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **fenceStatusChange** indicates a geofence status change. | - | request | GeofenceRequest | Yes | Geofencing request. | - | want | WantAgent | Yes | **WantAgent** used to return geofence (entrance or exit) events. | + | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| + | request | GeofenceRequest | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + - Example @@ -313,18 +359,22 @@ Registers a listener for status change events of the specified geofence. ``` -## geolocation.off('fenceStatusChange') +## geolocation.off('fenceStatusChange')8+ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; Unregisters the listener for status change events of the specified geofence. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **fenceStatusChange** indicates a geofence status change. | - | request | GeofenceRequest | Yes | Geofencing request. | - | want | WantAgent | Yes | **WantAgent** used to return geofence (entrance or exit) events. | + | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| + | request | GeofenceRequest | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| - Example @@ -381,14 +431,17 @@ Unregisters the listener for status change events of the specified geofence. getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void -Obtains the current location. This method uses an asynchronous callback to return the result. +Obtains the current location. This API uses an asynchronous callback to return the result. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No | Location request. | - | callback | AsyncCallback<[Location](#location)> | Yes | Callback used to return the current location. | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| - Example @@ -407,18 +460,22 @@ Obtains the current location. This method uses an asynchronous callback to retur getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> -Obtains the current location. This method uses a promise to return the result. +Obtains the current location. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No | Location request. | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the current location. | + | Promise<[Location](#location)> | Promise used to return the current location.| + - Example @@ -434,12 +491,17 @@ Obtains the current location. This method uses a promise to return the result. getLastLocation(callback: AsyncCallback<Location>) : void -Obtains the previous location. This method uses an asynchronous callback to return the result. +Obtains the previous location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Location](#location)> | Yes | Callback used to return the previous location. | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the previous location.| + - Example @@ -454,12 +516,17 @@ Obtains the previous location. This method uses an asynchronous callback to retu getLastLocation() : Promise<Location> -Obtains the previous location. This method uses a promise to return the result. +Obtains the previous location. This API uses a promise to return the result. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the previous location. | + | Promise<[Location](#location)> | Promise used to return the previous location.| + - Example @@ -475,13 +542,17 @@ Obtains the previous location. This method uses a promise to return the result. isLocationEnabled(callback: AsyncCallback<boolean>) : void -Checks whether the location service is enabled. This method uses an asynchronous callback to return the result. +Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the location service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + - Example @@ -496,12 +567,16 @@ Checks whether the location service is enabled. This method uses an asynchronous isLocationEnabled() : Promise<boolean> -Checks whether the location service is enabled. This method uses a promise to return the result. +Checks whether the location service is enabled. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION -- Return values - | Name | Description | +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status. | + | Promise<boolean> | Promise used to return the location service status.| - Example @@ -517,13 +592,17 @@ Checks whether the location service is enabled. This method uses a promise to re requestEnableLocation(callback: AsyncCallback<boolean>) : void -Requests to enable the location service. This method uses an asynchronous callback to return the result. +Requests to enable the location service. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the location service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + - Example @@ -538,12 +617,17 @@ Requests to enable the location service. This method uses an asynchronous callba requestEnableLocation() : Promise<boolean> -Requests to enable the location service. This method uses a promise to return the result. +Requests to enable the location service. This API uses a promise to return the result. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status. | + | Promise<boolean> | Promise used to return the location service status.| + - Example @@ -554,16 +638,127 @@ Requests to enable the location service. This method uses a promise to return th ``` +## geolocation.enableLocation + +enableLocation(callback: AsyncCallback<boolean>) : void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + + +- Example + + ``` + geolocation.enableLocation((err, data) => { + console.log('enableLocation: ' + err + " data: " + data); + }); + ``` + + +## geolocation.enableLocation + +enableLocation() : Promise<boolean> + +Enables the location service. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the location service status.| + + +- Example + + ``` + geolocation.enableLocation().then((result) => { + console.log('promise, enableLocation: ' + result); + }); + ``` + +## geolocation.disableLocation + +disableLocation(callback: AsyncCallback<boolean>) : void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + + +- Example + + ``` + geolocation.disableLocation((err, data) => { + console.log('disableLocation: ' + err + " data: " + data); + }); + ``` + + +## geolocation.disableLocation + +disableLocation() : Promise<boolean> + +Enables the location service. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the location service status.| + + +- Example + + ``` + geolocation.disableLocation().then((result) => { + console.log('promise, disableLocation: ' + result); + }); + ``` + ## geolocation.isGeoServiceAvailable isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void -Checks whether the (reverse) geocoding service is available. This method uses an asynchronous callback to return the result. +Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the (reverse) geocoding service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| + - Example @@ -578,12 +773,17 @@ Checks whether the (reverse) geocoding service is available. This method uses an isGeoServiceAvailable() : Promise<boolean> -Checks whether the (reverse) geocoding service is available. This method uses a promise to return the result. +Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the (reverse) geocoding service status. | + | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| + - Example @@ -599,13 +799,17 @@ Checks whether the (reverse) geocoding service is available. This method uses a getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void -Converts coordinates into geographic description through reverse geocoding. This method uses an asynchronous callback to return the result. +Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse geocoding request. | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes | Callback used to return the reverse geocoding result. | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| - Example @@ -621,17 +825,21 @@ Converts coordinates into geographic description through reverse geocoding. This getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; -Converts coordinates into geographic description through reverse geocoding. This method uses a promise to return the result. +Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse geocoding request. | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result. | + | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| - Example @@ -647,13 +855,18 @@ Converts coordinates into geographic description through reverse geocoding. This getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void -Converts geographic description into coordinates through geocoding. This method uses an asynchronous callback to return the result. +Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding request. | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes | Callback used to return the geocoding result. | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| + - Example @@ -669,17 +882,21 @@ Converts geographic description into coordinates through geocoding. This method getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> -Converts geographic description into coordinates through geocoding. This method uses a promise to return the result. +Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding request. | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the geocoding result. | + | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| - Example @@ -692,16 +909,20 @@ Converts geographic description into coordinates through geocoding. This method -## geolocation.getCachedGnssLocationsSize +## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; -Obtains the number of cached GNSS locations. +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes | Callback used to return the number of cached GNSS locations. | + | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | - Example @@ -712,16 +933,20 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.getCachedGnssLocationsSize +## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize() : Promise<number>; -Obtains the number of cached GNSS locations. +Obtains the number of cached GNSS locations. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +- Return value + | Name| Description| | -------- | -------- | - | Promise<number> | Promise used to return the number of cached GNSS locations. | + | Promise<number> | Promise used to return the number of cached GNSS locations.| - Example @@ -732,16 +957,20 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.flushCachedGnssLocations +## geolocation.flushCachedGnssLocations8+ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; -Obtains all cached GNSS locations and clears the GNSS cache queue. +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -752,16 +981,20 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.flushCachedGnssLocations +## geolocation.flushCachedGnssLocations8+ flushCachedGnssLocations() : Promise<boolean>; -Obtains all cached GNSS locations and clears the GNSS cache queue. +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. | + | Promise<boolean> | Promise used to return the operation result.| - Example @@ -772,17 +1005,21 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.sendCommand +## geolocation.sendCommand8+ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; -Sends an extended command to the location subsystem. This function can only be called by system applications. +Sends an extended command to the location subsystem. This API can only be called by system applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes | Extended command (string) to be sent. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | command | LocationCommand | Yes| Extended command (string) to be sent.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -794,21 +1031,25 @@ Sends an extended command to the location subsystem. This function can only be c ``` -## geolocation.sendCommand +## geolocation.sendCommand8+ sendCommand(command: LocationCommand) : Promise<boolean>; -Sends extended commands to the location subsystem. This function can only be called by system applications. +Sends an extended command to the location subsystem. This API can only be called by system applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes | Extended command (string) to be sent. | + | command | LocationCommand | Yes| Extended command (string) to be sent.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result. | + | Promise<boolean> | Callback used to return the operation result.| - Example @@ -820,17 +1061,23 @@ Sends extended commands to the location subsystem. This function can only be cal ``` -## geolocation.isLocationPrivacyConfirmed +## geolocation.isLocationPrivacyConfirmed8+ isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; -Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications. +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result, which indicates whether the user agrees with the privacy statement. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - Example @@ -841,21 +1088,27 @@ Checks whether a user agrees with the privacy statement of the location service. ``` -## geolocation.isLocationPrivacyConfirmed +## geolocation.isLocationPrivacyConfirmed8+ isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications. +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the result, which indicates whether the user agrees with the privacy statement. | + | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - Example @@ -866,18 +1119,24 @@ Checks whether a user agrees with the privacy statement of the location service. ``` -## geolocation.setLocationPrivacyConfirmStatus +## geolocation.setLocationPrivacyConfirmStatus8+ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications. +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | isConfirmed | boolean | Yes | Whether the user agrees with the privacy statement of the location service. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -888,22 +1147,28 @@ Sets the user confirmation status for the privacy statement of the location serv ``` -## geolocation.setLocationPrivacyConfirmStatus +## geolocation.setLocationPrivacyConfirmStatus8+ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications. +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | isConfirmed | boolean | Yes | Whether the user agrees with the privacy statement of the location service. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. | + | Promise<boolean> | Callback used to return the operation result.| - Example @@ -919,201 +1184,262 @@ Sets the user confirmation status for the privacy statement of the location serv Sets the priority of the location request. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| UNSET | 0x200 | Priority unspecified. | -| ACCURACY | 0x201 | Location accuracy. | -| LOW_POWER | 0x202 | Power efficiency. | -| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible. | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| ## LocationRequestScenario Sets the scenario of the location request. - | Name | Default Value | Description | + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| UNSET | 0x300 | Scenario unspecified. | -| NAVIGATION | 0x301 | Navigation. | -| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking. | -| CAR_HAILING | 0x303 | Ride hailing. | -| DAILY_LIFE_SERVICE | 0x304 | Daily life services. | -| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location. | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| ## GeoLocationErrorCode Enumerates error codes of the location service. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters. | -| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API. | -| GEOCODE_ERROR | 103 | Failed to call the geocoding API. | -| LOCATOR_ERROR | 104 | Failed to obtain the location. | -| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch. | -| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location. | -| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time. | +| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time.| ## ReverseGeoCodeRequest Defines a reverse geocoding request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| latitude | number | Yes | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | Yes | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| maxItems | number | No | Maximum number of location records to be returned. | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | No| Maximum number of location records to be returned.| ## GeoCodeRequest Defines a geocoding request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| description | number | Yes | Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**. | -| maxItems | number | No | Maximum number of location records to be returned. | -| minLatitude | number | No | Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges. | -| minLongitude | number | No | Minimum longitude. | -| maxLatitude | number | No | Maximum latitude. | -| maxLongitude | number | No | Maximum longitude. | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| +| maxItems | number | No| Maximum number of location records to be returned.| +| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| +| minLongitude | number | No| Minimum longitude.| +| maxLatitude | number | No| Maximum latitude.| +| maxLongitude | number | No| Maximum longitude.| ## GeoAddress Defines a geographic location. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| placeName | string | No | Landmark of the location. | -| countryCode | string | No | Country code. | -| countryName | string | No | Country name. | -| administrativeArea | string | No | Administrative region name. | -| subAdministrativeArea | string | No | Sub-administrative region name. | -| locality | string | No | Locality information. | -| subLocality | string | No | Sub-locality information. | -| roadName | string | No | Road name. | -| subRoadName | string | No | Auxiliary road information. | -| premises | string | No | House information. | -| postalCode | string | No | Postal code. | -| phoneNumber | string | No | Phone number. | -| addressUrl | string | No | Website URL. | -| descriptions | Array<string> | No | Additional description. | -| descriptionsSize | number | No | Total number of additional descriptions. | +| latitude | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName | string | No| Landmark of the location.| +| countryCode | string | No| Country code.| +| countryName | string | No| Country name.| +| administrativeArea | string | No| Administrative region name.| +| subAdministrativeArea | string | No| Sub-administrative region name.| +| locality | string | No| Locality information. | +| subLocality | string | No| Sub-locality information. | +| roadName | string | No| Road name.| +| subRoadName | string | No| Auxiliary road information.| +| premises | string | No| House information.| +| postalCode | string | No| Postal code.| +| phoneNumber | string | No| Phone number.| +| addressUrl | string | No| Website URL.| +| descriptions | Array<string> | No| Additional description.| +| descriptionsSize | number | No| Total number of additional descriptions.| ## LocationRequest Defines a location request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority of the location request. | -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes | Scenario of the location request. | -| timeInterval | number | No | Time interval at which location information is reported. | -| distanceInterval | number | No | Distance interval at which location information is reported. | -| maxAccuracy | number | No | Location accuracy. | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| +| timeInterval | number | No| Time interval at which location information is reported.| +| distanceInterval | number | No| Distance interval at which location information is reported.| +| maxAccuracy | number | No| Location accuracy.| ## CurrentLocationRequest Defines the current location request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority of the location request. | -| scenario | [LocationRequestScenario](#locationrequestscenario) | No | Scenario of the location request. | -| maxAccuracy | number | No | Location accuracy, in meters. | -| timeoutMs | number | No | Timeout duration, in milliseconds. The minimum value is **1000**. | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| +| maxAccuracy | number | No| Location accuracy, in meters.| +| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| -## SatelliteStatusInfo +## SatelliteStatusInfo8+ Defines the satellite status information. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes | Number of satellites. | -| satelliteIds | Array<number> | Yes | Array of satellite IDs. | -| carrierToNoiseDensitys | Array<number> | Yes | Carrier-to-noise density ratio, that is, cn0. | -| altitudes | Array<number> | Yes | Altitude information. | -| azimuths | Array<number> | Yes | Azimuth information. | -| carrierFrequencies | Array<number> | Yes | Carrier frequency. | +| satellitesNumber | number | Yes| Number of satellites.| +| satelliteIds | Array<number> | Yes| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| Altitude information.| +| azimuths | Array<number> | Yes| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| Carrier frequency.| -## CachedGnssLocationsRequest +## CachedGnssLocationsRequest8+ Represents a request for reporting cached GNSS locations. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | Yes | Interval for reporting the cached GNSS locations, in milliseconds. | -| wakeUpCacheQueueFull | boolean | Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full. | +| reportingPeriodSec | number | Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| -## Geofence +## Geofence8+ Defines a GNSS geofence. Currently, only circular geofences are supported. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes | Latitude information. | -| longitude | number | Yes | Longitude information. | -| radius | number | Yes | Radius of a circular geofence. | -| expiration | number | Yes | Expiration period of a geofence, in milliseconds. | +| latitude | number | Yes| Latitude information.| +| longitude | number | Yes| Longitude information.| +| radius | number | Yes| Radius of a circular geofence.| +| expiration | number | Yes| Expiration period of a geofence, in milliseconds.| -## GeofenceRequest +## GeofenceRequest8+ Represents a GNSS geofencing request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | Yes | Priority of the location information. | -| scenario | LocationRequestScenario | Yes | Location scenario. | -| geofence | Geofence | Yes | Geofence information. | +| priority | LocationRequestPriority | Yes| Priority of the location information.| +| scenario | LocationRequestScenario | Yes| Location scenario.| +| geofence | Geofence | Yes| Geofence information.| -## LocationPrivacyType +## LocationPrivacyType8+ Defines the privacy statement type. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| OTHERS | 0 | Other scenarios. | -| STARTUP | 1 | Privacy statement displayed in the startup wizard. | -| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service. | +| OTHERS | 0 | Other scenarios.| +| STARTUP | 1 | Privacy statement displayed in the startup wizard.| +| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| -## LocationCommand +## LocationCommand8+ Defines an extended command. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | Yes | Location scenario. | -| command | string | Yes | Extended command, in the string format. | +| scenario | LocationRequestScenario | Yes| Location scenario.| +| command | string | Yes| Extended command, in the string format.| ## Location Defines a location. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | Yes | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| altitude | number | Yes | Location altitude, in meters. | -| accuracy | number | Yes | Location accuracy, in meters. | -| speed | number | Yes | Speed, in m/s. | -| timeStamp | number | Yes | Location timestamp in the UTC format. | -| direction | number | Yes | Direction information. | -| timeSinceBoot | number | Yes | Location timestamp since boot. | -| additions | Array<string> | No | Additional description. | -| additionSize | number | No | Number of additional descriptions. | +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude | number | Yes| Location altitude, in meters.| +| accuracy | number | Yes| Location accuracy, in meters.| +| speed | number | Yes| Speed, in m/s.| +| timeStamp | number | Yes| Location timestamp in the UTC format.| +| direction | number | Yes| Direction information.| +| timeSinceBoot | number | Yes| Location timestamp since boot.| +| additions | Array<string> | No| Additional information.| +| additionSize | number | No| Number of additional descriptions.| diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index 0e5074650a..612f81c279 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -333,8 +333,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | HashMap | No| Instance that invokes the **forEach** method.| **Example** @@ -351,7 +351,7 @@ hashMap.forEach((value, key) => { ### entries -entries(): IterableIterator<[K, V]> +entries(): IterableIterator<[K, V]> Obtains an iterator that contains all the entries in this container. @@ -359,7 +359,7 @@ Obtains an iterator that contains all the entries in this container. | Type| Description| | -------- | -------- | -| IterableIterator<[K, V]> | Iterator obtained.| +| IterableIterator<[K, V]> | Iterator obtained.| **Example** @@ -387,7 +387,7 @@ Obtains an iterator, each item of which is a JavaScript object. | Type| Description| | -------- | -------- | -| IterableIterator<[K, V]> | Iterator obtained.| +| IterableIterator<[K, V]> | Iterator obtained.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 0a85c59cf8..4e33216b1a 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -198,7 +198,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key | T | No| Key of the entry that is currently traversed (same as **value**).| | set | HashSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 0d8534643b..4ec4c1062d 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,4 +1,4 @@ -# Application dotting +# HiAppEvent > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -11,25 +11,22 @@ import hiAppEvent from '@ohos.hiAppEvent'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiAppEvent - - ## hiAppEvent.write write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. +Writes event information to the event file of the current day. This API supports JSON parameters and uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| eventName | string | Yes| App event name.| -| eventType | [EventType](#eventtype) | Yes| Application event type.| -| keyValues | object | Yes| Array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).| -| callback | AsyncCallback<void> | No| Callback used to process the received return value.
- The value **0** indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0** indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| +| eventType | [EventType](#eventtype) | Yes | Application event type. | +| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| +| callback | AsyncCallback<void> | No | Callback used to process the received return value.
-  Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously.
-  A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
-  A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file.| **Example** @@ -51,20 +48,22 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str write(eventName: string, eventType: EventType, keyValues: object): Promise<void> -Writes event information to the event file of the current day. This function supports JSON parameters and uses a promise to return the result. +Writes event information to the event file of the current day. This API supports JSON parameters and uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| eventName | string | Yes| App event name.| -| eventType | [EventType](#eventtype) | Yes| Application event type.| -| keyValues | object | Yes| Array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).| +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------------------------------------------------------ | +| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| +| eventType | [EventType](#eventtype) | Yes | Application event type. | +| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed.| **Example** @@ -87,16 +86,18 @@ configure(config: ConfigOption): boolean Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [ConfigOption](#configoption) | Yes| Configuration items for application event logging.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ------------------------ | +| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ----------------------------------------------------------- | | boolean | Returns **true** if the configuration is successful; returns **false** otherwise.| **Example** @@ -117,41 +118,49 @@ hiAppEvent.configure({ Provides the configuration items for application event logging. -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| disable | boolean | No| Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.| -| maxStorage | string | No| Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ------------------------------------------------------------ | +| disable | boolean | No | Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.| +| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.| ## EventType Enumerates event types. -| Name| Default Value| Description| -| -------- | -------- | -------- | -| FAULT | 1 | Fault event| -| STATISTIC | 2 | Statistical event| -| SECURITY | 3 | Security event| -| BEHAVIOR | 4 | Behavior event| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Default Value| Description | +| --------- | ------ | -------------- | +| FAULT | 1 | Fault event| +| STATISTIC | 2 | Statistical event| +| SECURITY | 3 | Security event| +| BEHAVIOR | 4 | Behavior event| ## Event Provides constants that define the names of all predefined events. -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| USER_LOGIN | string | Yes| No| User login event.| -| USER_LOGOUT | string | Yes| No| User logout event.| -| DISTRIBUTED_SERVICE_START | string | Yes| No| Distributed service startup event.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Readable| Writable| Description | +| ------------------------- | -------- | ---- | ---- | -------------------- | +| USER_LOGIN | string | Yes | No | User login event. | +| USER_LOGOUT | string | Yes | No | User logout event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| ## Param Provides constants that define the names of all predefined event parameters. -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| USER_ID | string | Yes| No| Custom user ID.| -| DISTRIBUTED_SERVICE_NAME | string | Yes| No| Distributed service name.| -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes| No| Distributed service instance ID.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Readable| Writable| Description | +| ------------------------------- | -------- | ---- | ---- | ------------------ | +| USER_ID | string | Yes | No | Custom user ID. | +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 70022fd021..eef977c21d 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -11,21 +11,19 @@ import hichecker from '@ohos.hichecker'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiChecker - -## Rule Constants +## Constants Provides the constants of all rule types. -| Name| Type| Description| +**System capability**: SystemCapability.HiviewDFX.HiChecker + +| Name | Type| Description | | ---------------------------------- | -------- | ------------------------------------------------------ | -| RULE_CAUTION_PRINT_LOG | BigInt | Alarm rule, which is programmed to print a log when an alarm is generated.| -| RULE_CAUTION_TRIGGER_CRASH | BigInt | Alarm rule, which is programmed to force the application to exit when an alarm is generated.| -| RULE_THREAD_CHECK_SLOW_PROCESS | BigInt | Caution rule, which is programmed to detect whether any time-consuming function is invoked.| -| RULE_CHECK_SLOW_EVENT | BigInt | Caution rule, which is programmed to detect whether the event distribution or processing time has exceeded the specified time threshold.| -| RULE_CHECK_ABILITY_CONNECTION_LEAK | BigInt | Caution rule, which is programmed to detect whether ability leakage has occurred.| +| RULE\_CAUTION\_PRINT\_LOG | BigInt | Alarm rule, which is programmed to print a log when an alarm is generated. | +| RULE\_CAUTION\_TRIGGER\_CRASH | BigInt | Alarm rule, which is programmed to force the application to exit when an alarm is generated. | +| RULE\_THREAD\_CHECK\_SLOW\_PROCESS | BigInt | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | +| RULE\_CHECK\_SLOW\_EVENT | BigInt | Caution rule, which is programmed to detect whether the event distribution or processing time has exceeded the specified time threshold.| +| RULE\_CHECK\_ABILITY\_CONNECTION\_LEAK| BigInt | Caution rule, which is programmed to detect whether ability leakage has occurred. | ## hichecker.addRule @@ -34,11 +32,13 @@ addRule(rule: BigInt): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be added.| +| rule | BigInt | Yes | Rule to be added.| **Example** @@ -57,11 +57,13 @@ removeRule(rule: BigInt): void Removes one or more rules. The removed rules will become ineffective. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be removed.| +| rule | BigInt | Yes | Rule to be removed.| **Example** @@ -80,9 +82,11 @@ getRule(): BigInt Obtains a collection of thread, process, and alarm rules that have been added. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Return value** -| Type| Description| +| Type | Description | | ------ | ---------------------- | | BigInt | Collection of added rules.| @@ -93,7 +97,7 @@ Obtains a collection of thread, process, and alarm rules that have been added. hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Obtain the collection of added rules. -hichecker.getRule(); // return 1n; +hichecker.getRule(); // Return 1n. ``` ## hichecker.contains @@ -102,15 +106,17 @@ contains(rule: BigInt): boolean Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be checked.| +| rule | BigInt | Yes | Rule to be checked.| **Return value** -| Type| Description| +| Type | Description | | ------- | ---------------------------------------------------------- | | boolean | Returns **true** if the rule exists in the collection of added rules; returns **false** otherwise.| @@ -121,6 +127,6 @@ Checks whether the specified rule exists in the collection of added rules. If th hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Check whether the added rule exists in the collection of added rules. -hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; -hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // return false; +hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Return true. +hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // Return false. ``` diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 7e2473e5f4..c0844b51cb 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -12,24 +12,22 @@ import hidebug from '@ohos.hidebug'; ``` -## System Capabilities -SystemCapability.HiviewDFX.HiProfiler.HiDebug - - ## hidebug.getNativeHeapSize getNativeHeapSize(): bigint Obtains the total size of the native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Total size of the native heap memory.| +**Return Value** +| Type | Description | +| ------ | --------------------------- | +| bigint | Total size of the native heap memory.| -- **Example** + +**Example** ``` let nativeHeapSize = hidebug.getNativeHeapSize(); ``` @@ -41,14 +39,16 @@ getNativeHeapAllocatedSize(): bigint Obtains the size of the allocated native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the allocated native heap memory.| +**Return Value** +| Type | Description | +| ------ | --------------------------------- | +| bigint | Size of the allocated native heap memory.| -- **Example** + +**Example** ``` let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); ``` @@ -60,14 +60,16 @@ getNativeHeapFreeSize(): bigint Obtains the size of the free native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the free native heap memory.| +**Return Value** +| Type | Description | +| ------ | ------------------------------- | +| bigint | Size of the free native heap memory.| -- **Example** + +**Example** ``` let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); ``` @@ -79,14 +81,16 @@ getPss(): bigint Obtains the PSS of this process. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | PSS of the process.| +**Return Value** +| Type | Description | +| ------ | ------------------------- | +| bigint | PSS of the process.| -- **Example** + +**Example** ``` let pss = hidebug.getPss(); ``` @@ -98,14 +102,16 @@ getSharedDirty(): bigint Obtains the size of the shared dirty memory of this process. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the shared dirty memory of the process.| +**Return Value** +| Type | Description | +| ------ | -------------------------- | +| bigint | Size of the shared dirty memory of the process.| -- **Example** + +**Example** ``` let sharedDirty = hidebug.getSharedDirty(); ``` @@ -117,11 +123,13 @@ startProfiling(filename : string) : void Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes| User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| +| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** @@ -141,6 +149,8 @@ stopProfiling() : void Stops the profiling method. `stopProfiling()` and `startProfiling()` are called in pairs. `stopProfiling()` always occurs after `startProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Example** ```js @@ -157,11 +167,13 @@ dumpHeapData(filename : string) : void Exports the heap data. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Parameters** -| Name| Type| Mandatory| Description| +| 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 app based on the specified `filename`.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index a2a02fd14c..13814a6e63 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -2,7 +2,7 @@ > **Note:** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -10,9 +10,6 @@ import hilog from '@ohos.hilog'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiLog ## hilog.debug @@ -20,14 +17,16 @@ debug(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the DEBUG level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -41,20 +40,22 @@ hilog.debug(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3 09-08 12:49:35.941 1547 2452 D FF00/testTag: 1: hello World 3.0 ``` -## **hilog.info** +## hilog.info info(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the INFO level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -74,14 +75,16 @@ warn(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the WARN level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -101,14 +104,16 @@ error(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the ERROR level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -128,14 +133,16 @@ fatal(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the FATAL level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -155,13 +162,15 @@ isLoggable(domain: number, tag: string, level: LogLevel) : boolean Checks whether printing is enabled for a domain, tag, or log level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | --------------------- | ---- | ------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| level | [LogLevel](#loglevel) | Yes| Log level.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior.| +| level | [LogLevel](#loglevel) | Yes | Log level. | **Example** @@ -173,10 +182,12 @@ hilog.isLoggable(0xFF00, "testTag", hilog.DEBUG); Enumerates event types. -| Name| Default Value| Description| +**System capability**: SystemCapability.HiviewDFX.HiLog + +| Name | Default Value| Description | | ----- | ------ | ----------- | | DEBUG | 3 | DEBUG level| -| INFO | 4 | INFO level| -| WARN | 5 | WARN level| +| INFO | 4 | INFO level | +| WARN | 5 | WARN level | | ERROR | 6 | ERROR level| | FATAL | 7 | FATAL level| diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index b5af74e563..9cd2fd38fb 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -82,7 +82,7 @@ Starts call chain tracing. This API works in synchronous manner. | name | string | Yes| Traced service name.| | flags | number | Yes| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag).| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -124,7 +124,7 @@ Obtains the trace ID. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -184,7 +184,7 @@ Creates a trace span. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -237,7 +237,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous | -------- | -------- | -------- | -------- | | id | [HiTraceId](#hitraceid) | Yes| **HiTraceId** instance.| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -265,7 +265,7 @@ Checks whether the specified trace flag in the **HiTraceId** instance is enabled | id | [HiTraceId](#hitraceid) | Yes| **HiTraceId** instance.| | flag | [HiTraceFlag](#hitraceflag) | Yes| Specified trace flag.| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index 17f62fb18b..ad7e023755 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -11,21 +11,18 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiTrace - - ## hiTraceMeter.startTrace startTrace(name: string, taskId: number): void -Starts a trace task. +Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For a specific example, refer to an example in [hiTraceMeter.finishTrace](#hitracemeterfinishtrace). +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| @@ -37,6 +34,7 @@ If the trace tasks with the same name are not performed at the same time, the sa ``` hiTraceMeter.startTrace("myTestFunc", 1); +hiTraceMeter.startTrace("myTestFunc", 1, 5); // The expected duration of the trace task is 5 ms. ``` @@ -48,6 +46,8 @@ Stops a trace task. To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in [startTrace](#hitracemeterstarttrace). +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| @@ -90,6 +90,8 @@ traceByValue(name: string, count: number): void Traces the value changes of a variable. +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md new file mode 100644 index 0000000000..804832a1d4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -0,0 +1,1191 @@ +# HUKS + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. +HUKS also provides APIs for applications to import or generate keys. + +## Modules to Import + +```js +import huks from '@ohos.security.huks' +``` +## HuksErrorCode + +Enumerates 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 failed.| +| 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_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_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| + + +## HuksKeyPurpose + +Represents the purpose (usage) of a key. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | The key is used to encrypt plain text.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | The key is used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | The key is used to sign data. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | The key is used to verify the signed data. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | The key is used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | The key is used for encrypted import. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | The key is exported in encrypted mode. | +| HUKS_KEY_PURPOSE_MAC | 128 | The key is used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | The key is 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_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.| + +## 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 | PKCS1_V1_5.| +| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (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 + +Represents the key length. + +**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. | + +## HuksKeyAlg + +Represents the algorithm used by a key. + +**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 algorithm. | +| HUKS_ALG_ED25519 | 102 | ED25519 algorithm.| +| HUKS_ALG_DH | 103 | DH. | + +## 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 | The key is imported by using the public key import API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using the private key generation API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using the key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is generated by using the key derivation 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 | Send the tag asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | Send the tag synchronously.| + +## 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 | Indicates the algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Indicates the purpose of a key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Indicates the key length. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Indicates the digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Indicates the padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Indicates the cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Indicates the key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Indicates the associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Indicates the field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | Indicates the IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Indicates the information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Indicates the salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Indicates the password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Indicates the number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Indicates the key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Indicates the main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Indicates the factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Indicates the type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Indicates the type of the algorithm used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Indicates the alias of the public key during key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Indicates the private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Indicates the public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Indicates the key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Indicates the size of the derived key. | +| 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 | Reserved. | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Indicates the challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Indicates the application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Indicates the device brand. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Indicates the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Indicates the product. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Indicates the device SN. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Indicates the device IMEI. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Indicates the device MEID. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Indicates the device manufacturer. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Indicates the device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Indicates the key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Indicates the device SOCID. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Indicates the device UDID. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Indicates the security credential used for the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Indicates the version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Indicates whether to use the tag of the alias passed during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Indicates the 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 | Indicates the 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 | Indicates the 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 | Indicates the 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 | Indicates the operating system version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | Indicates the operating system 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 + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This method 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 will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huksHuksKeyAlg.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_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE +}; +var options = { + properties: properties +}; +huks.generateKey(alias, options, function (err, data){}); +``` + +## huks.generateKey + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This method 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. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huksHuksKeyAlg.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_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE +}; +var options = { + properties: properties +}; +var result = huks.generateKey(alias, options); +``` + +## huks.deleteKey + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This method 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. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var emptyOptions = { + properties: [] +}; +huks.deleteKey(alias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This method 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).| + +**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. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var emptyOptions = { + properties: [] +}; +var result = huks.deleteKey(alias, emptyOptions); +``` + +## huks.getSdkVersion + +getSdkVersion(options: HuksOptions) : string + +Obtains the SDK version of the current system. + +**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.| + +**Example** + +```js +var emptyOptions = { + properties: [] +}; +var result = huks.getSdkVersion(emptyOptions); +``` + +## huks.importKey + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Key alias, which is used to hold the key pair.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key pair 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. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: 1024 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: HUKS_DIGEST_SHA1 +}; +var options = { + properties: properties, + inData: importText +}; +huks.importKey(keyAlias, options, function (err, data){}); +``` + +## huks.importKey + +importKey(keyAlias: string, options: HuksOptions) : Promise\ + +Imports a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Key alias, which is used to hold the key pair.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key pair 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. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: 1024 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: HUKS_DIGEST_SHA1 +}; +var options = { + properties: properties, + inData: importText +}; +var result = huks.importKey(keyAlias, options); +``` + +## huks.exportKey + +exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This method 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\<[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. For details about the error codes, see **HuksResult**.
**outData** contains the public key exported.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.exportKey(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.exportKey + +exportKey(keyAlias: string, options: HuksOptions) : Promise\ + +Exports a key. This method 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\<[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. For details about the error codes, see **HuksResult**.
**outData** contains the public key exported.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.exportKey(keyAlias, emptyOptions); +``` + +## huks.getKeyProperties + +getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Obtains key properties. This method 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\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.getKeyProperties + +getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ + +Obtains key properties. This method 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\<[HuksResult](#huksoptions)> | Promise used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.getKeyProperties(keyAlias, emptyOptions); +``` + +## huks.isKeyExist + +isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This method 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 used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.isKeyExist + +isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ + +Checks whether a key exists. This method 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 check.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.isKeyExist(keyAlias, emptyOptions); +``` + + +## huks.init + +init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Initializes a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| keyAlias | string | Yes | Alias of the target key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the **Init** operation.| + +**Example** + +```js +var alias = 'test001' +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.init(alias, options, function(err, data) { + if (err.code !== 0) { + console.log("test init err information: " + JSON.stringify(err)); + } else { + console.log(`test init data: ${JSON.stringify(data)}`); + } +}) +``` + +## huks.init + +init(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| keyAlias | string | Yes | Alias of the target key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| +| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the **Init** operation.| + +**Example** + +```js +var alias = 'test001' +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.init(alias, options).then((data) => { + console.log(`test init data: ${JSON.stringify(data)}`); + handle1 = data.handle1; + handle2 = data.handle2; + handle = { + "handle1": handle1, + "handle2": handle2 + }; +}).catch((err) => { + console.log("test init err information: " + JSON.stringify(err)) +}) +``` + + +## huks.update + +update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void + +Updates a key. This method uses an asynchronous callback to return the result. + +**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 | Parameter set of the **Update** operation.| +| callback | AsyncCallback\<[HksResult](#hksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.update(handle, options, function (err, data){}); +``` + +## huks.update + +update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ + +Updates a key. This method uses a promise to return the result. + +**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 | Parameter set of the **Update** operation.| +| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.update(handle, options) +``` + +## huks.finish + +finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This method 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 | Parameter set of the **Finish** operation.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.finish(handle, options, function (err, data){}); +``` + +## huks.finish + +finish(handle: number, options: HuksOptions) : Promise\ + +Completes the key operation and releases resources. This method uses a promise 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 | Parameter set of the **Finish** operation.| +| promise | Promise\<[HuksResult](#HuksResult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.finish(handle, options) +``` + + +## huks.abort + +abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This method uses an asynchronous callback 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 | Parameter set of the **Abort** operation.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.abort(handle, options, function (err, data){}); +``` + +## huks.abort + +abort(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This method 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 | Parameter set of the **Abort** operation.| +| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.abort(handle, options); +``` + +## 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 | 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\ | No | Array used to hold **HuksParam**.| +| inData | Uint8Array | No | Input data. | + +## HuksHandle + +Defines the HUKS handle structure. + +**System capability**: SystemCapability.Security.Huks + +| Name | Type | Mandatory| Description | +| ---------- | ---------------- | ---- | -------- | +| errorCode | number | Yes | Error code.| +| handle | number | Yes| Value of the handle.| +| token | Uint8Array | No| Reserved field.| + + +## HuksResult + +Defines the **HuksResult** structure. + +**System capability**: SystemCapability.Security.Huks + + + +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | -------- | +| errorCode | number | Yes | Error code. | +| outData | Uint8Array | No | Output data.| +| properties | Array\ | No | Properties. | +| certChains | Array\ | No | Certificate chain. | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index f262500a4c..757c0733f1 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -2,7 +2,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > - This module contains enhanced i18n APIs, which are not defined in ECMA 402. @@ -21,19 +21,19 @@ Obtains the localized script for the specified language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Specified language.| - | locale | string | Yes| Locale ID.| - | sentenceCase | boolean | No| Whether to use sentence case for the localized script.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------- | +| language | string | Yes | Specified language. | +| locale | string | Yes | Locale ID. | +| sentenceCase | boolean | No | Whether to use sentence case for the localized script.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Localized script for the specified language.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Localized script for the specified language.| -- Example +**Example** ``` i18n.getDisplayLanguage("zh", "en-GB", true); i18n.getDisplayLanguage("zh", "en-GB"); @@ -48,26 +48,26 @@ Obtains the localized script for the specified country. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | country | string | Yes| Specified country.| - | locale | string | Yes| Locale ID.| - | sentenceCase | boolean | No| Whether to use sentence case for the localized script.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------- | +| country | string | Yes | Specified country. | +| locale | string | Yes | Locale ID. | +| sentenceCase | boolean | No | Whether to use sentence case for the localized script.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Localized script for the specified country.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Localized script for the specified country.| -- Example +**Example** ``` i18n.getDisplayCountry("zh-CN", "en-GB", true); i18n.getDisplayCountry("zh-CN", "en-GB"); ``` -## i18n.isRTL8+ +## i18n.isRTL7+ isRTL(locale: string): boolean @@ -75,17 +75,17 @@ Checks whether the localized script for the specified language is displayed from **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | locale | string | Locale ID.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------- | +| locale | string | Locale ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.| -- Example +**Example** ``` i18n.isRTL("zh-CN");// Since Chinese is not written from right to left, false is returned. i18n.isRTL("ar-EG");// Since Arabic is written from right to left, true is returned. @@ -100,12 +100,12 @@ Obtains the system language. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System language ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System language ID.| -- Example +**Example** ``` i18n.getSystemLanguage(); ``` @@ -117,19 +117,21 @@ setSystemLanguage(language: string): boolean Sets the system language. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | language | string | Language ID.| +**Parameters** +| Name | Type | Description | +| -------- | ------ | ----- | +| language | string | Language ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemLanguage('zh'); ``` @@ -137,18 +139,18 @@ Sets the system language. ## i18n.getSystemLanguages -getSystemLanguages(): Array +getSystemLanguages(): Array<string> Obtains the list of system languages. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of the IDs of system languages.| +**Return Value** +| Type | Description | +| ------------------- | ------------ | +| Array<string> | List of the IDs of system languages.| -- Example +**Example** ``` i18n.getSystemLanguages(); ``` @@ -156,23 +158,23 @@ Obtains the list of system languages. ## i18n.getSystemCountries -getSystemCountries(language: string): Array +getSystemCountries(language: string): Array<string> Obtains the list of countries and regions supported for the specified language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | language | string | Language ID.| +**Parameters** +| Name | Type | Description | +| -------- | ------ | ----- | +| language | string | Language ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of the IDs of the countries and regions supported for the specified language.| +**Return Value** +| Type | Description | +| ------------------- | ------------ | +| Array<string> | List of the IDs of the countries and regions supported for the specified language.| -- Example +**Example** ``` i18n.getSystemCountries('zh'); ``` @@ -186,12 +188,12 @@ Obtains the system region. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System region ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System region ID.| -- Example +**Example** ``` i18n.getSystemRegion(); ``` @@ -203,19 +205,21 @@ setSystemRegion(region: string): boolean Sets the system region. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | region | string | Region ID.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | ----- | +| region | string | Region ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemRegion(); ``` @@ -229,12 +233,12 @@ Obtains the system locale. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System locale ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System locale ID.| -- Example +**Example** ``` i18n.getSystemLocale(); ``` @@ -246,19 +250,21 @@ setSystemLocale(locale: string): boolean Sets the system locale. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | locale | string | System locale ID, for example, **zh-CN**.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | --------------- | +| locale | string | System locale ID, for example, **zh-CN**.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemLocale('zh-CN'); ``` @@ -272,18 +278,18 @@ Checks whether the system language matches the specified region. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Valid language ID, for example, **zh**.| - | region | string | No| Valid region ID, for example, **CN**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------- | +| language | string | Yes | Valid language ID, for example, **zh**.| +| region | string | No | Valid region ID, for example, **CN**. | -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.| -- Example +**Example** ``` i18n.isSuggested('zh', 'CN'); ``` @@ -297,18 +303,18 @@ Obtains a **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Valid locale value, for example, **zh-Hans-CN**.| - | type | string | No| Valid calendar type. Currently, the valid types are as follows: **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic\_civil**, **islamic\_tbla**, **islamic\_umalqura**, **japanese**, and **persian**. If this parameter is left unspecified, the default calendar type of the specified locale is used.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. | +| type | string | No | Valid calendar type. Currently, the valid types are as follows: **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic\_civil**, **islamic\_tbla**, **islamic\_umalqura**, **japanese**, and **persian**. If this parameter is left unspecified, the default calendar type of the specified locale is used.| -- Return value - | Type| Description| - | -------- | -------- | - | [Calendar](#calendar8) | **Calendar** object.| +**Return Value** +| Type | Description | +| ---------------------- | ----- | +| [Calendar](#calendar8) | **Calendar** object.| -- Example +**Example** ``` i18n.getCalendar("zh-Hans", "gregory"); ``` @@ -325,12 +331,12 @@ Sets the date for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | Yes| Date to be set for the **Calendar** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ----------------- | +| date | Date | Yes | Date to be set for the **Calendar** object.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); var date = new Date(2021, 10, 7, 8, 0, 0, 0); @@ -346,12 +352,12 @@ Sets the date and time for this **Calendar** object. The value is represented by **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | time | number | Yes| Number of milliseconds that have elapsed since the Unix epoch.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| time | number | Yes | Number of milliseconds that have elapsed since the Unix epoch.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); @@ -366,17 +372,17 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | year | number | Yes| Year to set.| - | month | number | Yes| Month to set.| - | date | number | Yes| Day to set.| - | hour | number | No| Hour to set.| - | minute | number | No| Minute to set.| - | second | number | No| Second to set.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------ | +| year | number | Yes | Year to set. | +| month | number | Yes | Month to set. | +| date | number | Yes | Day to set. | +| hour | number | No | Hour to set.| +| minute | number | No | Minute to set.| +| second | number | No | Second to set. | -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 @@ -391,12 +397,12 @@ Sets the time zone of this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | timezone | string | Yes| Time zone, for example, **Asia/Shanghai**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------- | +| timezone | string | Yes | Time zone, for example, **Asia/Shanghai**.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); @@ -411,12 +417,12 @@ Obtains the time zone of this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Time zone of the **Calendar** object.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Time zone of the **Calendar** object.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); @@ -432,12 +438,12 @@ Obtains the start day of a week for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +**Return Value** +| Type | Description | +| ------ | --------------------- | +| number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); calendar.getFirstDayOfWeek(); @@ -452,12 +458,12 @@ Sets the start day of a week for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | No| Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | --------------------- | +| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setFirstDayOfWeek(0); @@ -472,12 +478,12 @@ Obtains the minimum number of days in the first week of a year. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Minimum number of days in the first week of a year.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| number | Minimum number of days in the first week of a year.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.getMinimalDaysInFirstWeek(); @@ -492,12 +498,12 @@ Sets the minimum number of days in the first week of a year. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | No| Minimum number of days in the first week of a year.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------ | +| value | number | No | Minimum number of days in the first week of a year.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); @@ -512,17 +518,17 @@ Obtains the value of the specified field in the **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Value of the specified field in the **Calendar** object. Currently, a valid field can be any of the following: **era**, **year**, **month**, **week\_of\_year**, **week\_of\_month**, **date**, **day\_of\_year**, **day\_of\_week**, **day\_of\_week\_in\_month**, **hour**, **hour\_of\_day**, **minute**, **second**, **millisecond**, **zone\_offset**, **dst\_offset**, **year\_woy**, **dow\_local**, **extended\_year**, **julian\_day**, **milliseconds\_in\_day**, **is\_leap\_month**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| field | string | Yes | Value of the specified field in the **Calendar** object. Currently, a valid field can be any of the following: **era**, **year**, **month**, **week\_of\_year**, **week\_of\_month**, **date**, **day\_of\_year**, **day\_of\_week**, **day\_of\_week\_in\_month**, **hour**, **hour\_of\_day**, **minute**, **second**, **millisecond**, **zone\_offset**, **dst\_offset**, **year\_woy**, **dow\_local**, **extended\_year**, **julian\_day**, **milliseconds\_in\_day**, **is\_leap\_month**.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 @@ -538,17 +544,17 @@ Obtains the name of the **Calendar** object displayed for the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Locale for which the name of the **Calendar** object is displayed. For example, if **locale** is **en-US**, the name of the Buddhist calendar will be **Buddhist Calendar**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Locale for which the name of the **Calendar** object is displayed. For example, if **locale** is **en-US**, the name of the Buddhist calendar will be **Buddhist Calendar**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Name of the **Calendar** object displayed for the specified locale.| +**Return Value** +| Type | Description | +| ------ | ------------------- | +| string | Name of the **Calendar** object displayed for the specified locale.| -- Example +**Example** ``` var calendar = i18n.getCalendar("en-US", "buddhist"); calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. @@ -563,17 +569,17 @@ Checks whether the specified date in this **Calendar** object is a weekend. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | No| Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ---------------------------------------- | +| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the date is a weekend; returns **false** if the date is a weekday.| +**Return Value** +| Type | Description | +| ------- | ----------------------------------- | +| boolean | Returns **true** if the date is a weekend; returns **false** if the date is a weekday.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 @@ -595,12 +601,12 @@ Creates a **PhoneNumberFormat** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes| Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No| Options of the **PhoneNumberFormat** object.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------- | +| country | string | Yes | Country or region to which the phone number to be formatted belongs.| +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | -- Example +**Example** ``` var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -614,17 +620,17 @@ Checks whether the format of the specified phone number is valid. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | string | Yes| Phone number to be checked.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------- | +| number | string | Yes | Phone number to be checked.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.| -- Example +**Example** ``` var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); phonenumberfmt.isValidNumber("15812312312"); @@ -639,17 +645,17 @@ Formats a phone number. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | string | Yes| Phone number to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------- | +| number | string | Yes | Phone number to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Formatted phone number.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Formatted phone number.| -- Example +**Example** ``` var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); phonenumberfmt.format("15812312312"); @@ -662,9 +668,9 @@ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| type | string | Yes| Yes| Format type of a phone number. The value can be **E164**, **INTERNATIONAL**, **NATIONAL**, or **RFC3966**.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | Yes | Yes | Format type of a phone number. The value can be **E164**, **INTERNATIONAL**, **NATIONAL**, or **RFC3966**.| ## UnitInfo8+ @@ -673,10 +679,10 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| unit | string | Yes| Yes| Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| -| measureSystem | string | Yes| Yes| Measurement system. The value can be **SI**, **US**, or **UK**.| +| Name | Type | Readable | Writable | Description | +| ------------- | ------ | ---- | ---- | ---------------------------------------- | +| unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| +| measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| ## Util8+ @@ -690,21 +696,21 @@ Converts one measurement unit into another and formats the unit based on the spe **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fromUnit | [UnitInfo](#unitinfo8) | Yes| Measurement unit to be converted.| - | toUnit | [UnitInfo](#unitinfo8) | Yes| Measurement unit to be converted to.| - | value | number | Yes| Value of the measurement unit to be converted.| - | locale | string | Yes| Locale used for formatting, for example, **zh-Hans-CN**.| - | style | string | No| Style used for formatting. The value can be **long**, **short**, or **medium**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| fromUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted. | +| toUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted to. | +| value | number | Yes | Value of the measurement unit to be converted. | +| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. | +| style | string | No | Style used for formatting. The value can be **long**, **short**, or **medium**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.| +**Return Value** +| Type | Description | +| ------ | ----------------------- | +| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.| -- Example +**Example** ``` I18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); ``` @@ -718,17 +724,17 @@ Creates an **IndexUtil** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | No| A string containing locale information, including the language, optional script, and region.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------- | +| locale | string | No | A string containing locale information, including the language, optional script, and region.| -- Return value - | Type| Description| - | -------- | -------- | - | [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the specified locale.| +**Return Value** +| Type | Description | +| ------------------------ | --------------------- | +| [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the specified locale.| -- Example +**Example** ``` var indexUtil= i18n.IndexUtil.getInstance("zh-CN"); ``` @@ -745,12 +751,12 @@ Obtains the index list for this **locale** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array<string> | Index list for this **locale** object.| +**Return Value** +| Type | Description | +| ------------------- | ------------------ | +| Array<string> | Index list for this **locale** object.| -- Example +**Example** ``` var indexUtil = i18n.getInstance("zh-CN"); var indexList = indexUtil.getIndexList(); @@ -765,12 +771,12 @@ Adds the index of the new **locale** object to the index list. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| A string containing locale information, including the language, optional script, and region.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -- Example +**Example** ``` var indexUtil = i18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); @@ -785,17 +791,17 @@ Obtains the index of a text object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | text | string | Yes| **text** object whose index is to be obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| text | string | Yes | **text** object whose index is to be obtained.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Index of the **text** object.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | Index of the **text** object.| -- Example +**Example** ``` var indexUtil= i18n.getInstance("zh-CN"); indexUtil.getIndex("hi"); // Return h. @@ -813,17 +819,17 @@ Checks whether the input character string is composed of digits. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a digit; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.| -- Example +**Example** ``` var isdigit = Character.isDigit("1"); // Return true. ``` @@ -837,17 +843,17 @@ Checks whether the input character is a space. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a space; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Returns **true** if the input character is a space; returns **false** otherwise.| -- Example +**Example** ``` var isspacechar = Character.isSpaceChar("a"); // Return false. ``` @@ -861,17 +867,17 @@ Checks whether the input character is a white space. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a white space; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.| -- Example +**Example** ``` var iswhitespace = Character.isWhitespace("a"); // Return false. ``` @@ -885,17 +891,17 @@ Checks whether the input character is of the right to left (RTL) language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.| -- Example +**Example** ``` var isrtl = Character.isRTL("a"); // Return false. ``` @@ -909,17 +915,17 @@ Checks whether the input character is an ideographic character. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.| -- Example +**Example** ``` var isideograph = Character.isIdeograph("a"); // Return false. ``` @@ -933,17 +939,17 @@ Checks whether the input character is a letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.| -- Example +**Example** ``` var isletter = Character.isLetter("a"); // Return true. ``` @@ -957,17 +963,17 @@ Checks whether the input character is a lowercase letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.| -- Example +**Example** ``` var islowercase = Character.isLowerCase("a"); // Return true. ``` @@ -981,17 +987,17 @@ Checks whether the input character is an uppercase letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.| -- Example +**Example** ``` var isuppercase = Character.isUpperCase("a"); // Return false. ``` @@ -1005,17 +1011,17 @@ Obtains the type of the input character string. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Type of the input character.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | Type of the input character.| -- Example +**Example** ``` var type = Character.getType("a"); ``` @@ -1029,17 +1035,17 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Valid locale value, for example, **zh-Hans-CN**. The [BreakIterator](#breakiterator8) object segments text according to the rules of the specified locale.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. The [BreakIterator](#breakiterator8) object segments text according to the rules of the specified locale.| -- Return value - | Type| Description| - | -------- | -------- | - | [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.| +**Return Value** +| Type | Description | +| -------------------------------- | ----------- | +| [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.| -- Example +**Example** ``` i18n.getLineInstance("en"); ``` @@ -1056,12 +1062,12 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | text | string | Yes| Text to be processed by the **BreakIterator** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------- | +| text | string | Yes | Text to be processed by the **BreakIterator** object.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1076,12 +1082,12 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Text being processed by the **BreakIterator** object.| +**Return Value** +| Type | Description | +| ------ | ---------------------- | +| string | Text being processed by the **BreakIterator** object.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1097,12 +1103,12 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the **BreakIterator** object in the text being processed.| +**Return Value** +| Type | Description | +| ------ | --------------------------- | +| number | Position of the **BreakIterator** object in the text being processed.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1118,12 +1124,12 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset to the first text boundary of the processed text.| +**Return Value** +| Type | Description | +| ------ | ----------------- | +| number | Offset to the first text boundary of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1139,12 +1145,12 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset of the last text boundary of the processed text.| +**Return Value** +| Type | Description | +| ------ | ------------------ | +| number | Offset of the last text boundary of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1160,17 +1166,17 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | index | number | No| Number of text boundaries by which the [BreakIterator](#breakiterator8) object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as **1**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| index | number | No | Number of text boundaries by which the [BreakIterator](#breakiterator8) object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as **1**.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved by the specified number of text boundaries. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved by the specified number of text boundaries. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1188,12 +1194,12 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved to the previous text boundary. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved to the previous text boundary. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1211,17 +1217,17 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | offset | number | Yes| Offset to the position before the text boundary to which the [BreakIterator](#breakiterator8) object is moved.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| offset | number | Yes | Offset to the position before the text boundary to which the [BreakIterator](#breakiterator8) object is moved.| -- Return value - | Type| Description| - | -------- | -------- | - | number | The value **-1** is returned if the text boundary to which the [BreakIterator](#breakiterator8) object is moved is outside of the processed text.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | The value **-1** is returned if the text boundary to which the [BreakIterator](#breakiterator8) object is moved is outside of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1239,17 +1245,17 @@ Checks whether the position specified by the offset is a text boundary. If **tru **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | offset | number | Yes| Position to check.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----------- | +| offset | number | Yes | Position to check.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the position specified by the offset is a text boundary; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the position specified by the offset is a text boundary; returns **false** otherwise.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1258,7 +1264,7 @@ Checks whether the position specified by the offset is a text boundary. If **tru ``` -## i18n.is24HourClock8+ +## i18n.is24HourClock7+ is24HourClock(): boolean @@ -1266,36 +1272,38 @@ Checks whether the 24-hour clock is used. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.| -- Example +**Example** ``` var is24HourClock = i18n.is24HourClock(); ``` -## i18n.set24HourClock8+ +## i18n.set24HourClock7+ set24HourClock(option: boolean): boolean Sets the 24-hour clock. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | option | boolean | Yes| Whether to enable the 24-hour clock. The value **true** means to enable the 24-hour clock, and the value **false** means the opposite.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | ---------------------------------------- | +| option | boolean | Yes | Whether to enable the 24-hour clock. The value **true** means to enable the 24-hour clock, and the value **false** means the opposite.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.| -- Example +**Example** ``` // Set the system time to the 24-hour clock. var success = I18n.set24HourClock(true); @@ -1308,20 +1316,22 @@ addPreferredLanguage(language: string, index?: number): boolean Adds a preferred language to the specified position on the preferred language list. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Preferred language to add.| - | index | number | No| Position to which the preferred language is added.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ---------- | +| language | string | Yes | Preferred language to add. | +| index | number | No | Position to which the preferred language is added.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.| -- Example +**Example** ``` // Add zh-CN to the preferred language list. var language = 'zh-CN'; @@ -1336,19 +1346,21 @@ removePreferredLanguage(index: number): boolean Deletes a preferred language from the specified position on the preferred language list. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | index | number | Yes| Position of the preferred language to delete.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | --------------------- | +| index | number | Yes | Position of the preferred language to delete.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.| -- Example +**Example** ``` // Delete the first preferred language from the preferred language list. var index = 0; @@ -1358,18 +1370,18 @@ Deletes a preferred language from the specified position on the preferred langua ## i18n.getPreferredLanguageList8+ -getPreferredLanguageList(): Array +getPreferredLanguageList(): Array<string> Obtains the list of preferred languages. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of preferred languages.| +**Return Value** +| Type | Description | +| ------------------- | --------- | +| Array<string> | List of preferred languages.| -- Example +**Example** ``` var preferredLanguageList = i18n.getPreferredLanguageList(); ``` @@ -1383,18 +1395,18 @@ Obtains the first language in the preferred language list. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | First language in the preferred language list.| +**Return Value** +| Type | Description | +| ------ | -------------- | +| string | First language in the preferred language list.| -- Example +**Example** ``` var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); ``` -## i18n.getTimeZone8+ +## i18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1402,17 +1414,17 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | zondID | string | No| Time zone ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| zondID | string | No | Time zone ID.| -- Return value - | Type| Description| - | -------- | -------- | - | TimeZone | **TimeZone** object corresponding to the time zone ID.| +**Return Value** +| Type | Description | +| -------- | ------------ | +| TimeZone | **TimeZone** object corresponding to the time zone ID.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); ``` @@ -1429,12 +1441,12 @@ Obtains the ID of the specified **TimeZone** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Time zone ID corresponding to the **TimeZone** object.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| string | Time zone ID corresponding to the **TimeZone** object.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getID(); @@ -1449,18 +1461,18 @@ Obtains the representation of a **TimeZone** object in the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | No| System locale ID.| - | isDST | boolean | No| Whether to consider DST when obtaining the representation of the **TimeZone** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| locale | string | No | System locale ID. | +| isDST | boolean | No | Whether to consider DST when obtaining the representation of the **TimeZone** object.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Representation of the **TimeZone** object in the specified locale.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Representation of the **TimeZone** object in the specified locale.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getDisplayName("zh-CN", false); @@ -1475,12 +1487,12 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.| +**Return Value** +| Type | Description | +| ------ | ------------------- | +| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getRawOffset(); @@ -1495,12 +1507,12 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point.| +**Return Value** +| Type | Description | +| ------ | ----------------------- | +| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getOffset(1234567890); diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 8a112fc22b..3fd4d48c7b 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,18 +1,16 @@ -Image Processing -========== +# Image Processing > **NOTE** -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - Modules to Import ---------- +## Modules to Import ``` import image from '@ohos.multimedia.image'; ``` ## image.createPixelMap8+ -createPixelMap(colors: ArrayBuffer, opts: InitializetionOptions): Promise\ +createPixelMap(colors: ArrayBuffer, options: InitializetionOptions): Promise\ Creates a **PixelMap** object. This API uses a promise to return the result. @@ -20,30 +18,28 @@ Creates a **PixelMap** object. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| colors | ArrayBuffer | Yes | Color array. | -| opts | [InitializetionOptions](#InitializationOptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| colors | ArrayBuffer | Yes | Color array. | +| options | [InitializetionOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** | Type | Description | | -------------------------------- | -------------- | -| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object created.| +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| **Example** ```js image.createPixelMap(Color, opts) .then((pixelmap) => { - expect(pixelmap !== null).assertTrue() - done() }) ``` ## image.createPixelMap8+ -createPixelMap(colors: ArrayBuffer, opts: InitializetionOptions) callback: AsyncCallback\): void +createPixelMap(colors: ArrayBuffer, options: InitializetionOptions, callback: AsyncCallback\): void Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. @@ -51,18 +47,16 @@ Creates a **PixelMap** object. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------- | -| colors | ArrayBuffer | Yes | Color array. | -| opts | [InitializetionOptions](#InitializationOptions8) | Yes | Pixel properties. | -| callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | -------------------------- | +| colors | ArrayBuffer | Yes | Color array. | +| options | [InitializetionOptions](#initializationoptions8) | Yes | Pixel properties. | +| callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js image.createPixelMap(Color, opts, (pixelmap) => { - expect(pixelmap !== null).assertTrue() - done() }) ``` @@ -100,25 +94,10 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u ```js pixelmap.readPixelsToBuffer(readBuffer).then(() => { - var bufferArr = new Uint8Array(readBuffer) - var res = true - for (var i = 0; i < bufferArr.length; i++) { - if (res) { - if (bufferArr[i] !== 0) { - res = false - console.info('TC_020 Success') - expect(true).assertTrue() - done() - break - } - } - } - if (res) { - console.info('TC_020 buffer is all empty') - expect(false).assertTrue() - done() - } - }) + // Called if the condition is met. + }).catch(error => { + // Called if no condition is met. + }) ``` ### readPixelsToBuffer7+ @@ -140,24 +119,6 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u ```js pixelmap.readPixelsToBuffer(readBuffer, () => { - var bufferArr = new Uint8Array(readBuffer) - var res = true - for (var i = 0; i < bufferArr.length; i++) { - if (res) { - if (bufferArr[i] !== 0) { - res = false - console.info('TC_020-1 Success') - expect(true).assertTrue() - done() - break - } - } - } - if (res) { - console.info('TC_020-1 buffer is all empty') - expect(false).assertTrue() - done() - } }) ``` @@ -185,28 +146,10 @@ Reads pixel map data in an area. This API uses a promise to return the data read ```js pixelmap.readPixels(area).then((data) => { - if(data !== null){ - var bufferArr = new Uint8Array(area.pixels); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - console.info('TC_021 buffer ' + bufferArr[i]); - if(res) { - if (bufferArr[i] == 0) { - res = false; - console.info('TC_021 Success'); - expect(true).assertTrue(); - done(); - break; - } - } - } - if (res) { - console.info('TC_021 buffer is all empty'); - expect(false).assertTrue() - done(); - } - } - }) + // Called if the condition is met. + }).catch(error => { + // Called if no condition is met. + }) ``` ### readPixels7+ @@ -227,22 +170,22 @@ Reads image pixel map data in an area. This API uses a callback to return the da **Example** ```js -pixelmap.readPixels(area,(data) => { - if(data !== null) { - var bufferArr = new Uint8Array(area.pixels); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - console.info('TC_021-1 buffer ' + bufferArr[i]); - if(res) { - if(bufferArr[i] == 0) { - res = false; - console.info('TC_021-1 Success'); - expect(true).assertTrue(); - done(); - break; - } - } - } +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err, pixelmap) => { + if(pixelmap == undefined){ + console.info('createPixelMap failed'); + expect(false).assertTrue(); + done(); + }else{ + const area = { pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} + pixelmap.readPixels(area, () => { + console.info('readPixels success'); + }) + } +}) ``` ### writePixels7+ @@ -257,7 +200,7 @@ Writes image pixel map data to an area. This API uses a promise to return the op | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | -------------------- | -| area | [PositionArea](#PositionArea7) | Yes | Area to which the pixel map data will be written.| +| area | [PositionArea](#positionarea7) | Yes | Area to which the pixel map data will be written.| **Return value** @@ -268,11 +211,39 @@ Writes image pixel map data to an area. This API uses a promise to return the op **Example** ```js -pixelMap.writePixels(area).then(() => { - console.log("Succeeded in writing pixels."); -}).catch((err) => { - console.error("Failed to write pixels."); -}); +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts) + .then( pixelmap => { + if (pixelmap == undefined) { + console.info('createPixelMap failed'); + expect(false).assertTrue() + done(); + } + const area = { pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } + } + var bufferArr = new Uint8Array(area.pixels); + for (var i = 0; i < bufferArr.length; i++) { + bufferArr[i] = i + 1; + } + + pixelmap.writePixels(area).then(() => { + const readArea = { pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + // region.size.width + x < opts.width, region.size.height + y < opts.height + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } + } + }) + }) + .catch(error => { + console.log('error: ' + error); + expect().assertFail(); + done(); + }) ``` ### writePixels7+ @@ -287,7 +258,7 @@ Writes image pixel map data to an area. This API uses a callback to return the o | Name | Type | Mandatory| Description | | --------- | ------------------------------ | ---- | ------------------------------ | -| area | [PositionArea](#PositionArea7) | Yes | Area to which the pixel map data will be written. | +| area | [PositionArea](#positionarea7) | Yes | Area to which the pixel map data will be written. | | callback: | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.| **Example** @@ -401,19 +372,7 @@ Obtains pixel map information about this image. This API uses a callback to retu **Example** ```js -pixelmap.getImageInfo((imageInfo) => { - if (imageInfo !== null) { - console.info('TC_024-1 imageInfo is ready') - expect(imageInfo.size.height == 4).assertTrue() - expect(imageInfo.size.width == 6).assertTrue() - expect(imageInfo.pixelFormat == 1).assertTrue() - done() - } else { - console.info('TC_024-1 imageInfo is empty') - expect(false).assertTrue() - done() - } - }) +pixelmap.getImageInfo((imageInfo) => {}) ``` ### getBytesNumberPerRow7+ @@ -433,11 +392,7 @@ Obtains the number of bytes in each line of the image pixel map. **Example** ```js -pixelmap.getBytesNumberPerRow().then((num) => { - console.info('TC_025 num is ' + num) - expect(num == expectNum).assertTrue() - done() - }) +rowCount = pixelmap.getBytesNumberPerRow() ``` ### getPixelBytesNumber7+ @@ -457,11 +412,7 @@ Obtains the total number of bytes of the image pixel map. **Example** ```js -pixelmap.getPixelBytesNumber().then((num) => { - console.info('TC_026 num is ' + num) - expect(num == expectNum).assertTrue() - done() - }) +pixelBytesNumber = pixelmap.getPixelBytesNumber() ``` ### release7+ @@ -481,9 +432,8 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -pixelmap.release() - expect(true).assertTrue() - done() + pixelmap.release().then(() => { }) + .catch(error => {}) ``` ### release7+ @@ -503,11 +453,7 @@ Releases this **PixelMap** object. This API uses a callback to return the result **Example** ```js -pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 success'); - done(); - }) +pixelmap.release(()=>{ }) ``` ## image.createImageSource @@ -526,9 +472,9 @@ Creates an **ImageSource** instance based on the URI. **Return value** -| Type | Description | -| --------------------------- | --------------------------------------- | -| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **null** otherwise.| +| Type | Description | +| --------------------------- | -------------------------------------------- | +| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| **Example** @@ -552,9 +498,9 @@ Creates an **ImageSource** instance based on the file descriptor. **Return value** -| Type | Description | -| --------------------------- | --------------------------------------- | -| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **null** otherwise.| +| Type | Description | +| --------------------------- | -------------------------------------------- | +| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| **Example** @@ -590,20 +536,7 @@ Obtains information about an image with the specified index. This API uses a cal **Example** ```js -it('TC_046', 0, async function (done) { - const imageSourceApi = image.createImageSource('/sdcard/test.jpg'); - if (imageSourceApi == null) { - console.info('TC_046 create image source failed'); - expect(false).assertTrue(); - done(); - } else { - imageSourceApi.getImageInfo(0,(error, imageInfo) => { - console.info('TC_046 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) - } - }) +imageSourceApi.getImageInfo(0,(error, imageInfo) => {}) ``` ### getImageInfo @@ -623,11 +556,7 @@ Obtains information about this image. This API uses a callback to return the inf **Example** ```js -imageSourceApi.getImageInfo(imageInfo => { - console.info('TC_045 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) +imageSourceApi.getImageInfo(imageInfo => {}) ``` ### getImageInfo @@ -654,11 +583,8 @@ Obtains information about an image with the specified index. This API uses a pro ```js imageSourceApi.getImageInfo(0) - .then(imageInfo => { - console.info('TC_047 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) + .then(imageInfo => {}) + .catch(error => {}) ``` ### getImageProperty7+ @@ -685,7 +611,9 @@ Obtains the value of a property with the specified index in this image. This API **Example** ```js -const w = imageSourceApi.getImageProperty("ImageWidth") +imageSourceApi.getImageProperty("BitsPerSample") + .then(data => {}) + .catch(error => {}) ``` ### getImageProperty7+ @@ -706,7 +634,7 @@ Obtains the value of a property with the specified index in this image. This API **Example** ```js -const w = imageSourceApi.getImageProperty("ImageWidth",w=>{}) +imageSourceApi.getImageProperty("BitsPerSample",(error,data) => {}) ``` ### getImageProperty7+ @@ -728,12 +656,12 @@ Obtains the value of a property in this image. This API uses a callback to retur **Example** ```js - imageSourceApi.getImageProperty("ImageWidth",PropertyOptions,(w)=>{}) +imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {}) ``` ### createPixelMap7+ -createPixelMap(index: number, options: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(options?: DecodingOptions): Promise\ Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. @@ -741,58 +669,46 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------------- | ---- | -------------------- | -| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| index | number | Yes | Image index. | -| AsyncCallback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------ | ---- | ---------- | +| options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| **Example** ```js -imageSourceApi.createPixelMap().then(pixelmap => { - console.info('TC_050-11 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap().then(pixelmap => {}) + .catch(error => {}) ``` ### createPixelMap7+ -createPixelMap(options: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(callback: AsyncCallback\): void -Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. +Creates a **PixelMap** object based on the default parameters. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Image **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js -let decodingOptions = { - sampleSize:1, - editable: true, - desiredSize:{ width:1, height:2}, - rotateDegrees:10, - desiredPixelFormat:1, - desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - }; - imageSourceApi.createPixelMap(0,decodingOptions, pixelmap => { - console.info('TC_050-1 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap(pixelmap => {}) ``` ### createPixelMap7+ -createPixelMap(opts: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(options: DecodingOptions, callback: AsyncCallback\): void Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. @@ -800,28 +716,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| opts | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | +| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js -let decodingOptions = { - sampleSize:1, - editable: true, - desiredSize:{ width:1, height:2}, - rotateDegrees:10, - desiredPixelFormat:1, - desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - index:1 - }; - imageSourceApi.createPixelMap(decodingOptions, pixelmap => { - console.info('TC_050-1 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap(decodingOptions, pixelmap => {}) ``` ### release @@ -841,12 +744,7 @@ Releases this **ImageSource** instance. This API uses a callback to return the r **Example** ```js -imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - expect(true).assertTrue(); - done(); - }) - } +imageSourceApi.release(() => {}) ``` ### release @@ -866,11 +764,7 @@ Releases this **ImageSource** instance. This API uses a promise to return the re **Example** ```js - imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - expect(true).assertTrue(); - done(); - }) +imageSourceApi.release().then(()=>{ }).catch(error => {}) ``` ## image.createImagePacker @@ -883,9 +777,9 @@ Creates an **ImagePacker** instance. **Return value** -| Type | Description | -| ----------- | ---------------------- | -| ImagePacker | **ImagePacker** instance created.| +| Type | Description | +| --------------------------- | --------------------- | +| [ImagePacker](#imagepacker) | **ImagePacker** instance created.| **Example** @@ -905,7 +799,60 @@ Provide APIs to pack images. Before calling any API in **ImagePacker**, you must ### packing -packing(source: ImageSource, option: PackingOption, callback: AsyncCallback>): void +packing(source: ImageSource, option: PackingOption, callback: AsyncCallback>): void + +Packs an image. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ---------------------------------- | +| source | [ImageSource](#imagesource) | Yes | Image to pack. | +| option | [PackingOption](#packingoption) | Yes | Option for image packing. | +| callback | AsyncCallback> | Yes | Callback used to return the packed data.| + +**Example** + +```js +let packOpts = { format:["image/jpeg"], quality:98 } +imagePackerApi.packing(imageSourceApi, packOpts, data => {}) +``` + +### packing + +packing(source: ImageSource, option: PackingOption): Promise> + +Packs an image. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| source | [ImageSource](#imagesource) | Yes | Image to pack.| +| option | [PackingOption](#packingoption) | Yes | Option for image packing.| + +**Return value** + +| Type | Description | +| :--------------------------- | :-------------------------------------------- | +| Promise> | Promise used to return the packed data.| + +**Example** + +```js +let packOpts = { format:["image/jpeg"], quality:98 } +imagePackerApi.packing(imageSourceApi, packOpts) + .then( data => { }) + .catch(error => {}) +``` + +### packing + +packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\): void Packs an image. This API uses a callback to return the result. @@ -915,24 +862,20 @@ Packs an image. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------------------------- | -| source | [ImageSource](#imagesource) | Yes | Image to pack. | +| source | [PixelMap](#pixelmap) | Yes | **PixelMap** object to pack. | | option | [PackingOption](#packingoption) | Yes | Option for image packing. | -| callback | AsyncCallback> | Yes | Callback used to return the packed data.| +| callback | AsyncCallback\ | Yes | Callback used to return the packed data.| **Example** ```js let packOpts = { format:["image/jpeg"], quality:98 } - imagePackerApi.packing(imageSourceApi, packOpts, data => { - console.info('TC_062-1 finished'); - expect(data !== null).assertTrue(); - done(); - }) +imagePackerApi.packing(pixelMapApi, packOpts, data => {}) ``` ### packing -packing(source: ImageSource, option: PackingOption): Promise> +packing(source: PixelMap, option: PackingOption): Promise> Packs an image. This API uses a promise to return the result. @@ -942,25 +885,22 @@ Packs an image. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | -------------- | -| source | [ImageSource](#imagesource) | Yes | Image to pack.| +| source | [PixelMap](#pixelmap) | Yes | **PixelMap** object to pack.| | option | [PackingOption](#packingoption) | Yes | Option for image packing.| **Return value** -| Type | Description | -| :---------------------- | :-------------------------------------------- | -| Promise> | Promise used to return the packed data.| +| Type | Description | +| :--------------------------- | :-------------------------------------------- | +| Promise> | Promise used to return the packed data.| **Example** ```js let packOpts = { format:["image/jpeg"], quality:98 } - imagePackerApi.packing(imageSourceApi, packOpts) - .then( data => { - console.info('TC_062 finished'); - expect(data !== null).assertTrue(); - done(); - }) +imagePackerApi.packing(pixelMapApi, packOpts) + .then( data => { }) + .catch(error => {}) ``` ### release @@ -980,10 +920,7 @@ Releases this **ImagePacker** instance. This API uses a callback to return the r **Example** ```js -imagePackerApi.release(()=>{ - console.info('TC_063-1 release'); - expect(true).assertTrue(); - done(); +imagePackerApi.release(()=>{}) ``` ### release @@ -1003,10 +940,8 @@ Releases this **ImagePacker** instance. This API uses a promise to return the re **Example** ```js -imagePackerApi.release(); - console.info('TC_063 release'); - expect(true).assertTrue(); - done(); + imagePackerApi.release().then(()=>{ + }).catch((error)=>{}) ``` ## PositionArea7+ @@ -1015,14 +950,14 @@ Describes area information in an image. **System capability**: SystemCapability.Multimedia.Image -| Name | Type | Readable| Writable| Description | -| ------ | ------------------ | ---- | ---- | -------------------- | -| pixels | ArrayBuffer | Yes | No | Pixels of the image. | -| offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes to read. | -| region | [Region](#region8) | Yes | No | Region to read or write.| +| Name | Type | Readable| Writable| Description | +| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | +| 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. | +| region | [Region](#region8) | 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** +## ImageInfo Describes image information. @@ -1055,40 +990,14 @@ Enumerates pixel map formats. | RGBA_8888 | 3 | RGBA_8888.| | RGB_565 | 2 | RGB_565. | -## AlphaType8+ - -Enumerates alpha types. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| -------- | ------ | ----------------------- | -| UNKNOWN | 0 | Unknown alpha type. | -| OPAQUE | 1 | There is no alpha or the image is fully transparent.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | - -## ScaleMode8+ - -Enumerates scale modes. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| --------------- | ------ | -------------------------------------------------- | -| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| -| FIT_TARGET_SIZE | 2 | Reduces the image size to the dimensions of the target. | - ## InitializationOptions8+ **System capability**: SystemCapability.Multimedia.Image | Name | Type | Readable| Writable| Description | | ----------- | ---------------------------------- | ---- | ---- | -------------- | -| alphaType | [AlphaType](#alphatype8) | Yes | Yes | Alpha type. | | editable | boolean | Yes | Yes | Whether the image is editable. | | pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. | -| scaleMode | [ScaleMode](#scalemode8) | Yes | Yes | Scale mode. | | size | [Size](#size) | Yes | Yes | Image size.| ## DecodingOptions7+ @@ -1100,22 +1009,22 @@ Describes the decoding options. | Name | Type | Readable| Writable| Description | | ------------------ | ---------------------------------- | ---- | ---- | ---------------- | | sampleSize | number | Yes | Yes | Thumbnail sampling size.| -| rotateDegrees | number | Yes | Yes | Rotation angle. | +| rotate | number | Yes | Yes | Rotation angle. | | editable | boolean | Yes | Yes | Whether the image is editable. | | desiredSize | [Size](#size) | Yes | Yes | Expected output size. | -| desiredRegion | [Region](#region8) | Yes | Yes | Region to decode. | +| desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | numer | Yes | Yes | Index of the image to decode. | -## Region8+ +## Region7+ Describes region information. **System capability**: SystemCapability.Multimedia.Image -| Name| Type | Readable| Writable| Description | -| ---- | ------------- | ---- | ---- | ---------- | -| size | [Size](#size) | Yes | Yes | Region size.| +| Name| Type | Readable| Writable| Description | +| ---- | ------------- | ---- | ---- | ------------ | +| size | [Size](#size) | Yes | Yes | Region size. | | x | number | Yes | Yes | X coordinate of the region.| | y | number | Yes | Yes | Y coordinate of the region.| @@ -1145,6 +1054,8 @@ Describes image properties. Describes the exchangeable image file format (Exif) information of an image. +**System capability**: SystemCapability.Multimedia.Image + | Name | Default Value | Description | | ----------------- | ----------------- | -------------------- | | BITS_PER_SAMPLE | "BitsPerSample" | Number of bytes in each pixel. | diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 0913e6e3ce..02b81d4a51 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -20,90 +20,187 @@ import inputDevice from '@ohos.multimodalInput.inputDevice'; getDeviceIds(callback: AsyncCallback<Array<number>>): void -Obtains the IDs of all input devices. This method uses an asynchronous callback to return the result. +Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - **Parameters** - | Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result. | +**Parameters** - **Example** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----- | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result.| + + +**Example** + +``` +export default { + data: { + deviceIds: Array, + }, + callback: function(ids) { + this.deviceIds = ids; + }, + testGetDeviceIds: function () { + console.info("InputDeviceJsTest---start---testGetDeviceIds"); + inputDevice.getDeviceIds(this.callback); + console.info("InputDeviceJsTest---end---testGetDeviceIds"); + } +} +``` + +## inputDevice.getDeviceIds + +function getDeviceIds(): Promise> + +Obtains the IDs of all input devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Return value** + +| Name | Description | +| ---------------------- | ------------------ | +| Promise> | Promise used to return the result.| + +**Example** ``` -data: { - deviceIds: Array, -}, -callback: function(ids) { - this.deviceIds = ids; -}, -testGetDeviceIds: function () { - console.info("InputDeviceJsTest---start---testGetDeviceIds"); - inputDevice.getDeviceIds(this.callback); - console.info("InputDeviceJsTest---end---testGetDeviceIds"); +export default { + testGetDeviceIds: function () { + console.info("InputDeviceJsTest---start---testGetDeviceIds"); + let promise = inputDevice.getDeviceIds(); + promise.then((data)=> { + console.info('GetDeviceIds successed, Data: ' + JSON.stringify(data)) + }).catch((err)=>{ + console.error('Failed GetDeviceIds. Cause: ' + JSON.stringify(err)); + }); + } } ``` + + + ## inputDevice.getDevice getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void -Obtains the information about an input device. This method uses an asynchronous callback to return the result. +Obtains the information about an input device. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - **Parameters** - | Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| deviceId | number | Yes | ID of the input device whose information is to be obtained. | -| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | Yes | Callback used to return the **InputDeviceData** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------- | +| deviceId | number | Yes | ID of the input device whose information is to be obtained. | +| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | Yes | Callback used to return the **InputDeviceData** object.| - **Example** +**Example** ``` -InputDeviceData { - deviceId : 0, - name : "NA", - sources : Array, - axisRanges : Array, -}, -callback: function(deviceData) { - this.InputDeviceData = deviceData; -}, -testGetDevice: function () { - // The example is used to obtain the information about the device whose ID is 1. - console.info("InputDeviceJsTest---start---testGetDevice"); - inputDevice.getDevice(1, this.callback); - console.info("InputDeviceJsTest---end---testGetDevice"); +export default { + InputDeviceData: { + deviceId : 0, + name : "NA", + sources : Array, + axisRanges : Array, + }, + callback: function(deviceData) { + this.InputDeviceData = deviceData; + }, + testGetDevice: function () { + // The example is used to obtain the information about the device whose ID is 1. + console.info("InputDeviceJsTest---start---testGetDevice"); + inputDevice.getDevice(1, this.callback); + console.info("InputDeviceJsTest---end---testGetDevice"); + } } ``` +## inputDevice.getDevice + +function getDevice(deviceId: number): Promise + +Obtains the information about an input device. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Return value** + +| Name | Description | +| ------------------------ | ------------------ | +| Promise | Promise used to return the result.| + +**Example** + +``` +export default { + InputDeviceData: { + deviceId : 0, + name : "NA", + sources : Array, + axisRanges : Array, + }, + testGetDevice: function () { + // The example is used to obtain the information about the device whose ID is 1. + console.info("InputDeviceJsTest---start---testGetDevice"); + let promise = inputDevice.getDevice(1); + promise.then((data)=> { + console.info('GetDeviceId successed, Data: ' + JSON.stringify(data)) + }).catch((err)=>{ + console.error('Failed GetDeviceId. Cause: ' + JSON.stringify(err)); + }); + } +} +``` + + ## InputDeviceData Defines the information about an input device. - **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - | Name | Type | Description | -| -------- | -------- | -------- | -| id | number | Unique identifier of an input device. If the same physical device is repeatedly inserted and removed, its ID changes. | -| name | string | Name of the input device. | -| sources | Array<[SourceType](#sourcetype)> | Source types of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad. | +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +| Name | Type | Description | +| ------- | -------------------------------------- | ---------------------------------------- | +| id | number | Unique identifier of an input device. If the same physical device is repeatedly inserted and removed, its ID changes. | +| name | string | Name of the input device. | +| sources | Array<[SourceType](#sourcetype)> | Source types of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| + +## AxisType + +Axis type. This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. + +## AxisRange + +Defines the axis information of an input device. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +| Name | Type | Description | +| ------ | ------------------------- | -------- | +| source | [SourceType](#sourcetype) | Input source type of the axis.| +| axis | [AxisType](axistype) | Axis type. | +| max | number | Maximum value reported by the axis. | +| min | number | Minimum value reported by the axis. | + ## SourceType -Enumerates the input source types. +Enumerates the input source types. For example, if a mouse reports an x-axis event, the source of the x-axis is the mouse. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - | Name | Type | Description | -| -------- | -------- | -------- | -| keyboard | string | The input device is a keyboard. | -| touchscreen | string | The input device is a touchscreen. | -| mouse | string | The input device is a mouse. | -| trackball | string | The input device is a trackball. | -| touchpad | string | The input device is a touchpad. | -| joystick | string | The input device is a joystick. | +| Name | Type | Description | +| ----------- | ------ | ----------- | +| keyboard | string | The input device is a keyboard. | +| touchscreen | string | The input device is a touchscreen.| +| mouse | string | The input device is a mouse. | +| trackball | string | The input device is a trackball.| +| touchpad | string | The input device is a touchpad.| +| joystick | string | The input device is a joystick.| diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md new file mode 100644 index 0000000000..ed3942bb59 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -0,0 +1,57 @@ +# Input Event Client + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs of this module are system APIs and cannot be called by third-party applications. + + +## Modules to Import + + +``` +import inputEventClient from '@ohos.multimodalInput.inputEventClient'; +``` + + +## inputEventClient.injectEvent + +injectEvent({KeyEvent: KeyEvent}): void + +Injects a key. + +**System capability**: SystemCapability.MultimodalInput.Input.InputSimulator + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| KeyEvent | [KeyEvent](#keyevent) | Yes| Information about the key to inject.| + +**Example** + +``` +let keyEvent = { + isPressed: true, + keyCode: 2, + keyDownDuration: 0, + isIntercepted: false +} +res = inputEventClient.injectEvent({KeyEvent: keyEvent}); +``` + + +## KeyEvent + +Defines the information about the key to inject. + +**System capability**: SystemCapability.MultimodalInput.Input.InputSimulator + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| isPressed | boolean | Yes| Whether the key is pressed.| +| keyCode | Number | Yes| Key code.| +| keyDownDuration | boolean | Yes| Duration for which the key is pressed.| +| isIntercepted | Number | Yes| Whether the key can be intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md new file mode 100644 index 0000000000..6e5ef326d3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -0,0 +1,208 @@ +# Input Method Framework + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import inputMethod from '@ohos.inputMethod'; +``` + +## inputMethod8+ + +Provides the constants. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| + + +## InputMethodProperty8+ + +Describes the input method application attributes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| packageName | string | Yes| No| Package name.| +| methodId | string | Yes| No| Ability name.| + +## inputMethod.getInputMethodController + +getInputMethodController(): InputMethodController + +Obtains an [InputMethodController](#InputMethodController) instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type| Description| + | -------- | -------- | + | [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.| + +- Example + ``` + var InputMethodController = inputMethod.getInputMethodController(); + ``` +## inputMethod.getInputMethodSetting8+ + +getInputMethodSetting(): InputMethodSetting + +Obtains an [InputMethodSetting](#InputMethodSetting) instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | ----------------------------------------- | ---------------------------- | + | [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.| + + +- Example + ``` + var InputMethodSetting = inputMethod.getInputMethodSetting(); + ``` + +## InputMethodController + +In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. + +### stopInput + +stopInput(callback: AsyncCallback<boolean>): void + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the keyboard is successfully hidden.| + +- Example + +``` + InputMethodController.stopInput((error)=>{ + console.info('stopInput'); + }); +``` + +### stopInput + +stopInput(): Promise<boolean> + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| + +- Example + + +``` + var isSuccess = InputMethodController.stopInput(); + console.info('stopInput isSuccess = ' + isSuccess); +``` + +## InputMethodSetting8+ + +In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. + +### listInputMethod + +listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>): void + +Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------------------- | ---- | ---------------------- | + | callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.| + +- Example + ``` + InputMethodSetting.listInputMethod((properties)=>{ + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + }); + ``` + +### listInputMethod + +listInputMethod(): Promise<Array<InputMethodProperty>> + +Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + | Type | Description | + | ----------------------------------------------------------- | ---------------------- | + | Promise> | Promise used to return the list of installed input methods.| + +- Example + ``` + var properties = InputMethodSetting.listInputMethod(); + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + ``` + +### displayOptionalInputMethod + +displayOptionalInputMethod(callback: AsyncCallback<void>): void + +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +- Example + ``` + InputMethodSetting.displayOptionalInputMethod(()=>{ + console.info('displayOptionalInputMethod is called'); + }); + ``` + +### displayOptionalInputMethod + +displayOptionalInputMethod(): Promise<void> + +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. + + **System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + + - Example + ``` + InputMethodSetting.displayOptionalInputMethod(); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md new file mode 100644 index 0000000000..ba43211b4a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -0,0 +1,756 @@ +# Input Method Engine + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import inputMethodEngine from '@ohos.inputMethodEngine'; +``` + +## inputMethodEngine + +Defines constant values. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ENTER_KEY_TYPE_UNSPECIFIED | number | Yes| No| No function is specified for the Enter key.| +| ENTER_KEY_TYPE_GO | number | Yes| No| The Enter key takes the user to the target.| +| ENTER_KEY_TYPE_SEARCH | number | Yes| No| The Enter key takes the user to the results of their searching.| +| ENTER_KEY_TYPE_SEND | number | Yes| No| The Enter key sends the text to its target.| +| ENTER_KEY_TYPE_NEXT | number | Yes| No| The Enter key takes the user to the next field.| +| ENTER_KEY_TYPE_DONE | number | Yes| No| The Enter key takes the user to the next line.| +| ENTER_KEY_TYPE_PREVIOUS | number | Yes| No| The Enter key takes the user to the previous field.| +| PATTERN_NULL | number | Yes| No| Any type of edit box.| +| PATTERN_TEXT | number | Yes| No| Text edit box.| +| PATTERN_NUMBER | number | Yes| No| Number edit box.| +| PATTERN_PHONE | number | Yes| No| Phone number edit box.| +| PATTERN_DATETIME | number | Yes| No| Date edit box.| +| PATTERN_EMAIL | number | Yes| No| Email edit box.| +| PATTERN_URI | number | Yes| No| URI edit box.| +| PATTERN_PASSWORD | number | Yes| No| Password edit box.| +| OPTION_ASCII | number | Yes| No| ASCII values are allowed.| +| OPTION_NONE | number | Yes| No| No input attribute is specified.| +| OPTION_AUTO_CAP_CHARACTERS | number | Yes| No| Characters are allowed.| +| OPTION_AUTO_CAP_SENTENCES | number | Yes| No| Sentences are allowed.| +| OPTION_AUTO_WORDS | number | Yes| No| Words are allowed.| +| OPTION_MULTI_LINE | number | Yes| No| Multiple lines are allowed.| +| OPTION_NO_FULLSCREEN | number | Yes| No| Half-screen style.| +| FLAG_SELECTING | number | Yes| No| The edit box is being selected.| +| FLAG_SINGLE_LINE | number | Yes| No| The edit box allows only single-line input.| +| DISPLAY_MODE_PART | number | Yes| No| The edit box is displayed in half-screen mode.| +| DISPLAY_MODE_FULL | number | Yes| No| The edit box is displayed in full screen.| + +## inputMethodEngine.getInputMethodEngine + +getInputMethodEngine(): InputMethodEngine + +Obtains an **InputMethodEngine** instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | --------------------------------------- | ------------ | + | [InputMethodEngine](#InputMethodEngine) | **InputMethodEngine** instance obtained.| + +- Example + + ``` + var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); + ``` + +## inputMethodEngine.createKeyboardDelegate + +createKeyboardDelegate(): KeyboardDelegate + +Obtains a **KeyboardDelegate** instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | ------------------------------------- | ---------------- | + | [KeyboardDelegate](#KeyboardDelegate) | **KeyboardDelegate** instance obtained.| + +- Example + + ``` + var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); + ``` + +## InputMethodEngine + +In the following API examples, you must first use [getInputMethodEngine](#getInputMethodEngine) to obtain an **InputMethodEngine** instance, and then call the APIs using the obtained instance. + +### on('inputStart') + +on(type: 'inputStart', callback: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void + +Listens for the input method binding event. This API uses a callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| +| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | Yes| Callback used to return the result.| + +- Example + + ``` + InputMethodEngine.on('inputStart', (kbController, textInputClient) => { + KeyboardController = kbController; + TextInputClient = textInputClient; + }); + ``` + +### off('inputStart') + +off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void + +Cancels listening for the input method binding event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| + | callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.| + + + +- Example + + ``` + InputMethodEngine.off('inputStart'); + ``` + +### on('keyboardShow'|'keyboardHide') + +on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void + +Listens for an input method event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| + | callback | void | No | Callback used to return the result. | + +- Example + + ``` + InputMethodEngine.on('keyboardShow', (err) => { + console.info('keyboardShow'); + }); + ``` + +### off('keyboardShow'|'keyboardHide') + +off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void + +Cancels listening for an input method event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| + | callback | void | No | Callback used to return the result. | + +- Example + + ``` + InputMethodEngine.off('keyboardShow'); + ``` + + +## KeyboardDelegate + +In the following API examples, you must first use [createKeyboardDelegate](#createKeyboardDelegate) to obtain a **KeyboardDelegate** instance, and then call the APIs using the obtained instance. + +### on('keyDown'|'keyUp') + +on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void + +Listens for a hard keyboard even. This API uses a callback to return the key information. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| + | callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| + + + +- Example + + ``` + KeyboardDelegate.on('keyDown', (event) => { + console.info('keyDown'); + }); + ``` + +### off('keyDown'|'keyUp') + +off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void + +Cancels listening for a hard keyboard even. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| + | callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | + +- Example + + ``` + KeyboardDelegate.off('keyDown'); + ``` + +### on('cursorContextChange') + +on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void + +Listens for cursor context changes. This API uses a callback to return the cursor information. + + **System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| + | callback | number | Yes | Callback used to return the cursor information. | + + + + - Example + + ``` + KeyboardDelegate.on('cursorContextChange', (x, y, height) => { + console.info('cursorContextChange'); + }); + ``` + +### off('cursorContextChange') + +off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void + +Cancels listening for cursor context changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| + | callback | number | No| Callback used to return the cursor information.| + + + - Example + + ``` + KeyboardDelegate.off('cursorContextChange'); + ``` +### on('selectionChange') + +on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void + +Listens for text selection changes. This API uses a callback to return the text selection information. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| + | callback | number | Yes | Callback used to return the text selection information. | + + - Example + + ``` + KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { + console.info('selectionChange'); + }); + ``` + +### off('selectionChange') + +off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void + +Cancels listening for text selection changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| + | callback | number | No| Callback used to return the text selection information.| + + - Example + + ``` + KeyboardDelegate.off('selectionChange'); + ``` + + +### on('textChange') + +on(type: 'textChange', callback: (text: string) => void): void + +Listens for text changes. This API uses a callback to return the current text content. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| + | callback | string | Yes| Callback used to return the current text content.| + + - Example + + ``` + KeyboardDelegate.on('textChange', (text) => { + console.info('textChange'); + }); + ``` + +### off('textChange') + +off(type: 'textChange', callback?: (text: string) => void): void + +Cancels listening for text changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| + | callback | string | No| Callback used to return the current text content.| + + - Example + + ``` + KeyboardDelegate.off('textChange'); + ``` + +## KeyboardController + +In the following API examples, you must first use [inputStart](#inputStart) to obtain a **KeyboardController** instance, and then call the APIs using the obtained instance. + +### hideKeyboard + +hideKeyboard(callback: AsyncCallback<void>): void + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | -------- | + | callback | AsyncCallback<void> | No | Callback used to return the result.| + +- Example + + +``` + KeyboardController.hideKeyboard(()=>{ + }); +``` + +### hideKeyboard + +hideKeyboard(): Promise<void> + +Hides the keyboard. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description: | + | ---------------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + + +``` + KeyboardController.hideKeyboard(); +``` + +## TextInputClient + +In the following API examples, you must first use [inputStart](#inputStart) to obtain a **TextInputClient** instance, and then call the APIs using the obtained instance. + +### getForward + +getForward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<string> | Yes| Text returned.| + +- Example + ``` + TextInputClient.getForward(5,(text) =>{ + console.info("text = " + text); + }); + ``` + +### getForward + +getForward(length:number): Promise<string> + +Obtains the specific-length text before the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<string> | Text returned. | + +- Example + ``` + var text = TextInputClient.getForward(5); + console.info("text = " + text); + ``` + +### getBackward + +getBackward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<string> | Yes| Text returned.| + +- Example + ``` + TextInputClient.getBackward(5,(text)=>{ + console.info("text = " + text); + }); + ``` + +### getBackward + +getBackward(length:number): Promise<string> + +Obtains the specific-length text after the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<string> | Text returned. | + +- Example + ``` + var text = TextInputClient.getBackward(5); + console.info("text = " + text); + ``` + +### deleteForward + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + +- Example + ``` + TextInputClient.deleteForward(5,(isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` +### deleteForward + +deleteForward(length:number): Promise<boolean> + +Deletes the fixed-length text before the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + + - Example + ``` + var isSuccess = TextInputClient.deleteForward(5); + console.info("isSuccess = " + isSuccess); + ``` + +### deleteBackward + +deleteBackward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + + - Example + ``` + TextInputClient.deleteBackward(5, (isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### deleteBackward + +deleteBackward(length:number): Promise<boolean> + +Deletes the fixed-length text after the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.deleteBackward(5); + console.info("isSuccess = " + isSuccess); + ``` +### sendKeyFunction + +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void + +Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | action | number | Yes| Edit box attribute.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + + - Example + ``` + TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### sendKeyFunction + +sendKeyFunction(action:number): Promise<boolean> + +Sets the Enter key to send the text to its target. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | action | number | Yes| Edit box attribute.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); + console.info("isSuccess = " + isSuccess); + ``` + +### insertText + +insertText(text:string, callback: AsyncCallback<boolean>): void + +Inserts text. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | text | string | Yes| Text to insert.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + +- Example + ``` + TextInputClient.insertText("test", (isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### insertText + +insertText(text:string): Promise<boolean> + +Inserts text. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | text | string | Yes| Text to insert.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.insertText("test"); + console.info("isSuccess = " + isSuccess); + ``` + +### getEditorAttribute + +getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void + +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name | Type | Mandatory | Description | + | ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | callback | AsyncCallback<[EditorAttribute](#EditorAttribute)> | Yes| Attribute of the edit box. | + +- Example + ``` + TextInputClient.getEditorAttribute((EditorAttribute)=>{ + }); + ``` + +### getEditorAttribute + +getEditorAttribute(): Promise<EditorAttribute> + +Obtains the attribute of the edit box. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<[EditorAttribute](#EditorAttribute)> | Returns the attribute of the edit box. | + +- Example + ``` + var EditorAttribute = TextInputClient.getEditorAttribute(); + ``` + +## EditorAttribute + +Describes the attribute of the edit box. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name | Type| Readable| Writable| Description | +| ------------ | -------- | ---- | ---- | ------------------ | +| enterKeyType | number | Yes | No | Function attribute of the edit box.| +| inputPattern | number | Yes | No | Text attribute of the edit box.| + +## KeyEvent + +Describes the attribute of a key. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ------------ | +| keyCode | number | Yes | No | Key value.| +| keyAction | number | Yes | No | Key status.| diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index b5cee97142..2bf1b68fd1 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > - The APIs of this module are system APIs and cannot be called by third-party applications. @@ -31,30 +31,32 @@ Starts listening for global input events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** - | Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the input event. Currently, only **touch** events are supported. | -| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| type | string | Yes | Type of the input event. Currently, only **touch** events are supported.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | **Example** ``` -callback: function (value) { - if (checkEvent(value)) { +export default { + callback: function (value) { + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOn: function () { + console.info("InputMonitorJsTest---start---testOn"); + inputMonitor.on( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOn"); } -}, -testOn: function () { - console.info("InputMonitorJsTest---start---testOn"); - inputMonitor.on( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOn"); } ``` @@ -70,31 +72,33 @@ Stops listening for global input events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** - | Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the input event. Currently, only **touch** events are supported. | -| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| type | string | Yes | Type of the input event. Currently, only **touch** events are supported.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | **Example** ``` -callback: function (value) { - if (checkEvent(value)) { +export default { + callback: function (value) { + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOff: function () { + console.info("InputMonitorJsTest---start---testOff"); + inputMonitor.off( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOff"); } -}, -testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); -} + } ``` @@ -105,38 +109,40 @@ Represents the class of the callback used to return the touch event. The value * ### (touchEvent: TouchEvent): Boolean -Represents the callback used to return the touch event. You need to define the name of the callback function in the correct format. Ensure that the input parameter is of the **TouchEvent** type, and the return value is of the **Boolean** type. +Represents the callback used to return the touch event. You need to define the name of the callback function in the correct format. Ensure that the input parameter is of the TouchEvent type, and the return value is of the Boolean type. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** -| Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event.| **Return value** - | Type | Description | -| -------- | -------- | -| Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite. | +| Type | Description | +| ------- | -------------------------------------- | +| Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite.| **Example** ``` -callback: function (value) {// Implementation of the (touchEvent:TouchEvent): Boolean API. - if (checkEvent(value)) { +export default { + callback: function (value) { // Implementation of the (touchEvent:TouchEvent): Boolean API. + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOff: function () { + console.info("InputMonitorJsTest---start---testOff"); + inputMonitor.off( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOff"); } -}, -testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); } ``` diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 8843ab1880..433672bb7d 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,8 +1,8 @@ # Internationalization – intl > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> - 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. +> > - This module contains standard i18n APIs, which are defined in ECMA 402. @@ -20,18 +20,18 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| No| Language associated with the locale, for example, **zh**.| -| script | string | Yes| No| Script type of the language, for example, **Hans**.| -| region | string | Yes| No| Region associated with the locale, for example, **CN**.| -| baseName | string | Yes| No| Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**.| -| caseFirst | string | Yes| No| Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes| No| Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes| No| Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes| No| Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| -| numberingSystem | string | Yes| No| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| numeric | boolean | Yes| No| Whether to apply special collation rules for numeric characters.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| language | string | Yes | No | Language associated with the locale, for example, **zh**. | +| script | string | Yes | No | Script type of the language, for example, **Hans**. | +| region | string | Yes | No | Region associated with the locale, for example, **CN**. | +| baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | +| caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | ### constructor8+ @@ -42,7 +42,7 @@ Creates a Locale object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var locale = new Intl.Locale(); ``` @@ -56,13 +56,13 @@ Creates a Locale object. **System capability**: SystemCapability.Global.I18n -- Parameters - | 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.| +**Parameters** +| 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. | -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); ``` @@ -76,12 +76,12 @@ Converts locale information to a string. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | String containing locale information.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | String containing locale information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.toString(); @@ -96,12 +96,12 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [Locale](#locale) | **Locale** object with the maximized information.| +**Return Value** +| Type | Description | +| ----------------- | ---------- | +| [Locale](#locale) | **Locale** object with the maximized information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.maximize(); @@ -116,12 +116,12 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [Locale](#locale) | **Locale** object with the minimized information.| +**Return Value** +| Type | Description | +| ----------------- | ---------- | +| [Locale](#locale) | **Locale** object with the minimized information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.minimize(); @@ -134,14 +134,14 @@ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| calendar | string | Yes| Yes| Calendar for the locale. The calue can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes| Yes| Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes| Yes| Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| numeric | boolean | Yes| Yes| Whether to use the 12-hour clock.| -| caseFirst | string | Yes| Yes| Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| calendar | string | Yes | Yes | Calendar for the locale. The calue can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | +| caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| ## DateTimeFormat @@ -155,7 +155,7 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat(); ``` @@ -163,25 +163,25 @@ Creates a **DateTimeOptions** object for the specified locale. ### constructor -constructor(locale: string | Array, options?: DateTimeOptions) +constructor(locale: string | Array<string>, options?: DateTimeOptions) Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| - | options | [DateTimeOptions](#datetimeoptions) | No| Options for creating a **DateTimeFormat** object.| +**Parameters** +| 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. | -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -195,17 +195,17 @@ Formats the specified date and time. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | Yes| Date and time to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ------- | +| date | Date | Yes | Date and time to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | A string containing the formatted date and time.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| string | A string containing the formatted date and time.| -- Example +**Example** ``` var date = new Date(2021, 11, 17, 3, 24, 0); var datefmt = new Intl.DateTimeFormat("en-GB"); @@ -221,18 +221,18 @@ Formats the specified date range. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | startDate | Date | Yes| Start date and time to be formatted.| - | endDate | Date | Yes| End date and time to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ---- | ---- | -------- | +| startDate | Date | Yes | Start date and time to be formatted.| +| endDate | Date | Yes | End date and time to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | A string containing the formatted date and time range.| +**Return Value** +| Type | Description | +| ------ | -------------- | +| string | A string containing the formatted date and time range.| -- Example +**Example** ``` var startDate = new Date(2021, 11, 17, 3, 24, 0); var endDate = new Date(2021, 11, 18, 3, 24, 0); @@ -249,12 +249,12 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +**Return Value** +| Type | Description | +| ----------------------------------- | ----------------------------- | +| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| -- Example +**Example** ``` var datefmt = new Intl.DateTimeFormat("en-GB"); datefmt.resolvedOptions(); @@ -267,27 +267,27 @@ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| No| Locale, for example, **zh-Hans-CN**.| -| dateStyle | string | Yes| Yes| Date display format. The value can be **long**, **short**, **medium**, or **full**.| -| timeStyle | string | Yes| Yes| Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes| Yes| Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| -| timeZone | string | Yes| Yes| Time zone represented by a valid IANA time zone ID.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| hour12 | boolean | Yes| Yes| Whether to use the 12-hour clock.| -| weekday | string | Yes| Yes| Workday display format. The value can be **long**, **short**, or **narrow**.| -| era | string | Yes| Yes| Era display format. The value can be **long**, **short**, or **narrow**.| -| year | string | Yes| Yes| Year display format. The value can be **numeric** or **2-digit**. | -| month | string | Yes| Yes| Month display format. The value can be any of the following: **numeric**, **2-digit**, **long**, **short**, **narrow**.| -| day | string | Yes| Yes| Day display format. The value can be **numeric** or **2-digit**.| -| hour | string | Yes| Yes| Hour display format. The value can be **numeric** or **2-digit**.| -| minute | string | Yes| Yes| Minute display format. The value can be **numeric** or **2-digit**.| -| second | string | Yes| Yes| Seconds display format. The value can be **numeric** or **2-digit**.| -| timeZoneName | string | Yes| Yes| Localized representation of a time zone name.| -| dayPeriod | string | Yes| Yes| Time period display format. The value can be **long**, **short**, or **narrow**.| -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| formatMatcher | string | Yes| Yes| Format matching algorithm. The value can be **basic** or **best fit**.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | +| dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| +| timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | +| weekday | string | Yes | Yes | Workday display format. The value can be **long**, **short**, or **narrow**.| +| era | string | Yes | Yes | Era display format. The value can be **long**, **short**, or **narrow**.| +| year | string | Yes | Yes | Year display format. The value can be **numeric** or **2-digit**. | +| month | string | Yes | Yes | Month display format. The value can be any of the following: **numeric**, **2-digit**, **long**, **short**, **narrow**.| +| day | string | Yes | Yes | Day display format. The value can be **numeric** or **2-digit**. | +| hour | string | Yes | Yes | Hour display format. The value can be **numeric** or **2-digit**. | +| minute | string | Yes | Yes | Minute display format. The value can be **numeric** or **2-digit**. | +| second | string | Yes | Yes | Seconds display format. The value can be **numeric** or **2-digit**. | +| timeZoneName | string | Yes | Yes | Localized representation of a time zone name. | +| dayPeriod | string | Yes | Yes | Time period display format. The value can be **long**, **short**, or **narrow**.| +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| formatMatcher | string | Yes | Yes | Format matching algorithm. The value can be **basic** or **best fit**.| ## NumberFormat @@ -301,7 +301,7 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(); ``` @@ -309,19 +309,19 @@ Creates a **NumberFormat** object for the specified locale. ### constructor -constructor(locale: string | Array, options?: NumberOptions) +constructor(locale: string | Array<string>, options?: NumberOptions) Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No| Options for creating a **NumberFormat** object.| +| 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. | -- Example +**Example** ``` var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -335,18 +335,18 @@ Formats a number. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | number | Yes| Number to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---- | +| number | number | Yes | Number to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Formatted number.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Formatted number.| -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.format(1223); @@ -361,13 +361,13 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +**Return Value** +| Type | Description | +| ------------------------------- | --------------------------- | +| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.resolvedOptions(); @@ -380,27 +380,27 @@ Provides the device capability. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| No| Locale, for example, **zh-Hans-CN**.| -| currency | string | Yes| Yes| Currency unit, for example, **EUR**, **CNY**, or **USD**.| -| currencySign | string | Yes| Yes| Currency unit symbol. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| -| currencyDisplay | string | Yes| Yes| Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| -| unit | string | Yes| Yes| Unit name, for example, **meter**, **inch**, or **hectare**.| -| unitDisplay | string | Yes| Yes| Unit display format. The value can be **long**, **short**, or **medium**.| -| unitUsage | string | Yes| Yes| Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| -| signDisplay | string | Yes| Yes| Number sign display format. The value can be **auto**, **never**, always**, or **expectZero**.| -| compactDisplay | string | Yes| Yes| Compact display format. The value can be **long** or **short**.| -| notation | string | Yes| Yes| Number formatting specification. The value can be **standard**, **scientific**, engineering**, or **compact**.| -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| style | string | Yes| Yes| Number display format. The value can be **decimal**, **currency**, **percent**, or **unit**.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| useGrouping | boolean | Yes| Yes| Whether to use grouping for display.| -| minimumIntegerDigits | number | Yes| Yes| Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**.| -| minimumFractionDigits | number | Yes| Yes| Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**.| -| maximumFractionDigits | number | Yes| Yes| Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**.| -| minimumSignificantDigits | number | Yes| Yes| Minimum number of the least significant digits. The value ranges from **1** to **21**.| -| maximumSignificantDigits | number | Yes| Yes| Maximum number of the least significant digits. The value ranges from **1** to **21**.| +| Name | Type | Readable | Writable | Description | +| ------------------------ | ------- | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | +| currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | +| currencySign | string | Yes | Yes | Currency unit symbol. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| +| currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| +| unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. | +| unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **medium**.| +| unitUsage | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| +| signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.| +| compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. | +| notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.| +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| style | string | Yes | Yes | Number display format. The value can be **decimal**, **currency**, **percent**, or **unit**.| +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| useGrouping | boolean | Yes | Yes | Whether to use grouping for display. | +| minimumIntegerDigits | number | Yes | Yes | Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**. | +| minimumFractionDigits | number | Yes | Yes | Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**. | +| maximumFractionDigits | number | Yes | Yes | Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**. | +| minimumSignificantDigits | number | Yes | Yes | Minimum number of the least significant digits. The value ranges from **1** to **21**. | +| maximumSignificantDigits | number | Yes | Yes | Maximum number of the least significant digits. The value ranges from **1** to **21**. | ## Collator8+ @@ -414,7 +414,7 @@ Creates a Collator object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var collator = new Intl.Collator(); ``` @@ -422,20 +422,20 @@ Creates a Collator object. ### constructor8+ -constructor(locale: string | Array, options?: CollatorOptions) +constructor(locale: string | Array<string>, options?: CollatorOptions) Creates a Collator object. **System capability**: SystemCapability.Global.I18n -- Parameters +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| - | options | [CollatorOptions](#collatoroptions) | No| Options for creating 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. | -- Example +**Example** ``` var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -449,18 +449,18 @@ Compares two strings based on the sorting policy of the **Collator** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | first | string | Yes| First string to compare.| - | second | string | Yes| Second string to compare.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------ | +| first | string | Yes | First string to compare. | +| second | string | Yes | Second string to compare.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| -- Example +**Example** ``` var collator = new Intl.Collator("zh-Hans"); collator.compare("first", "second"); @@ -475,12 +475,12 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +**Return Value** +| Type | Description | +| ----------------------------------- | ----------------- | +| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| -- Example +**Example** ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); @@ -493,15 +493,15 @@ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| usage | string | Yes| Yes| Whether the comparison is for sorting or for searching. The value can be **sort** or **search**.| -| sensitivity | string | Yes| Yes| Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| -| ignorePunctuation | boolean | Yes| Yes| Whether punctuation is ignored. The value can be **true** or **false**.| -| collation | string | Yes| Yes| Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| numeric | boolean | Yes| Yes| Whether numeric collation is used. The value can be **true** or **false**.| -| caseFirst | string | Yes| Yes| Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| +| Name | Type | Readable | Writable | Description | +| ----------------- | ------- | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | +| collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | +| caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| ## PluralRules8+ @@ -515,7 +515,7 @@ Create a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var pluralRules = new Intl.PluralRules(); ``` @@ -523,19 +523,19 @@ Create a **PluralRules** object. ### constructor8+ -constructor(locale: string | Array, options?: PluralRulesOptions) +constructor(locale: string | Array<string>, options?: PluralRulesOptions) Create a **PluralRules** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No| Options for creating a **PluralRules** object.| +| 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. | -- Example +**Example** ``` var pluralRules= new Intl.PluraRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -549,17 +549,17 @@ Obtains a string that represents the singular-plural type of the specified numbe **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | n | number | Yes| Number for which the singular-plural type is to be obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| n | number | Yes | Number for which the singular-plural type is to be obtained.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| -- Example +**Example** ``` var pluralRules = new Intl.PluralRules("zh-Hans"); pluralRules.select(1); @@ -572,15 +572,15 @@ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| type | string | Yes| Yes| Sorting type. The value can be **cardinal** or **ordinal**.| -| minimumIntegerDigits | number | Yes| Yes| Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**.| -| minimumFractionDigits | number | Yes| Yes| Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**.| -| maximumFractionDigits | number | Yes| Yes| Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**.| -| minimumSignificantDigits | number | Yes| Yes| Minimum number of the least significant digits. The value ranges from **1** to **21**.| -| maximumSignificantDigits | number | Yes| Yes| Maximum number of the least significant digits. The value ranges from **1** to **21**.| +| Name | Type | Readable | Writable | Description | +| ------------------------ | ------ | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | +| minimumIntegerDigits | number | Yes | Yes | Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**. | +| minimumFractionDigits | number | Yes | Yes | Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**. | +| maximumFractionDigits | number | Yes | Yes | Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**. | +| minimumSignificantDigits | number | Yes | Yes | Minimum number of the least significant digits. The value ranges from **1** to **21**. | +| maximumSignificantDigits | number | Yes | Yes | Maximum number of the least significant digits. The value ranges from **1** to **21**. | ## RelativeTimeFormat8+ @@ -594,7 +594,7 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -602,19 +602,19 @@ Creates a **RelativeTimeFormat** object. ### constructor8+ -constructor(locale: string | Array, options?: RelativeTimeFormatInputOptions) +constructor(locale: string | Array<string>, options?: RelativeTimeFormatInputOptions) Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No| Options for creating 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. | -- Example +**Example** ``` var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -628,18 +628,18 @@ Formats the value and unit based on the specified locale and formatting options. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Value to format.| - | unit | string | Yes| Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| value | number | Yes | Value to format. | +| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Relative time after formatting.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Relative time after formatting.| -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); relativetimefmt.format(3, "quarter") @@ -648,24 +648,24 @@ Formats the value and unit based on the specified locale and formatting options. ### formatToParts8+ -formatToParts(value: number, unit: string): Array +formatToParts(value: number, unit: string): Array<object> Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Value to format.| - | unit | string | Yes| Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| value | number | Yes | Value to format. | +| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -- Return value - | Type| Description| - | -------- | -------- | - | Array | An array of **RelativeTimeFormat** objects in parts.| +**Return Value** +| Type | Description | +| ------------------- | --------------------------- | +| Array<object> | An array of **RelativeTimeFormat** objects in parts.| -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); var parts = relativetimefmt.format(10, "seconds"); @@ -680,12 +680,12 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +**Return Value** +| Type | Description | +| ---------------------------------------- | --------------------------------- | +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| -- Example +**Example** ``` var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); relativetimefmt.resolvedOptions(); @@ -698,11 +698,11 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| numeric | string | Yes| Yes| Format of the output message. The value can be **always** or **auto**.| -| style | string | Yes| Yes| Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| +| Name | Type | Readable | Writable | Description | +| ------------- | ------ | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | +| style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| ## RelativeTimeFormatResolvedOptions8+ @@ -711,9 +711,9 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| Yes| A string containing locale information, including the language, optional script, and region.| -| numeric | string | Yes| Yes| Format of the output message. The value can be **always** or **auto**.| -| style | string | Yes| Yes| Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -| numberingSystem | string | Yes| Yes| Numbering system.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------ | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | +| numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | +| style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| +| numberingSystem | string | Yes | Yes | Numbering system. | diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index b61e3e25c5..063b77a636 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -524,8 +524,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | LightWeightMap | No| Instance that invokes the **forEach** method.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index 8d604ed7ac..768ffc337f 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -279,7 +279,7 @@ Removes the entry at the specified position from this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the entry.| **Return value** @@ -428,7 +428,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key| T | No| Key of the entry that is currently traversed (same as **value**).| | set | LightWeightSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index c90867ac6d..cebc8bbbf0 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -176,7 +176,7 @@ let result = linkedList.get(2); ### getLastIndexOf -getLastIndexOf(element: T): number; +getLastIndexOf(element: T): number Obtains the index of the last occurrence of the specified entry in this container. @@ -404,11 +404,10 @@ let result = linkedList.removeLastFound(4); ``` ### clone -clone(): LinkedList<T> -Clones this container and returns a copy. +clone(): LinkedList<T> -The modification to the copy does not affect the original instance. +Clones this container and returns a copy. The modification to the copy does not affect the original instance. **Return value** @@ -428,6 +427,7 @@ let result = linkedList.clone(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void @@ -462,6 +462,7 @@ linkedList.forEach((value, index) => { ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -478,6 +479,7 @@ linkedList.clear(); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. @@ -507,6 +509,7 @@ let result = linkedList.set(2, "b"); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -575,7 +578,7 @@ linkedList.getLast(); ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<T>; +[Symbol.iterator]\(): IterableIterator<T> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 7c39d49ce7..ad87462656 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -60,7 +60,7 @@ Adds an entry at the end of this container. **Example** ``` -let list = new List; +let list = new List(); let result = list.add("a"); let result1 = list.add(1); let b = [1, 2, 3]; @@ -160,7 +160,7 @@ Obtains the index of the last occurrence of the specified entry in this containe | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Entry to obtain.| **Return value** @@ -192,7 +192,7 @@ Obtains the index of the first occurrence of the specified entry in this contain | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Entry to obtain.| **Return value** @@ -310,6 +310,7 @@ let result = list.remove(2); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void @@ -347,6 +348,7 @@ list.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void @@ -382,6 +384,7 @@ list.forEach((value, index) => { ``` ### sort + sort(comparator: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -412,6 +415,7 @@ list.sort(a, (b => b - a)); ``` ### getSubList + getSubList(fromIndex: number, toIndex: number): List<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **List** instance. @@ -443,6 +447,7 @@ let result2 = list.subList(2, 6); ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -459,6 +464,7 @@ list.clear(); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. @@ -489,6 +495,7 @@ list.set(2, "b"); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -511,6 +518,7 @@ let result = list.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -547,7 +555,7 @@ Obtains the first entry in this container. **Example** ``` -let list = new Vector(); +let list = new List(); list.add(2); list.add(4); list.add(5); @@ -570,7 +578,7 @@ Obtains the last entry in this container. **Example** ``` -let list = new Vector(); +let list = new List(); list.add(2); list.add(4); list.add(5); @@ -580,7 +588,7 @@ let result = list.getLast(); ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<T>; +[Symbol.iterator]\(): IterableIterator<T> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index 864ce3ecc2..e2d0aff5a5 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,174 +1,69 @@ -# Console Logs +# Log -## Module to Import +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead. -No module is required. +## console.debug -## Required Permissions +debug(message: string): void -None +Prints debug logs. -## console.debug +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| -debug\(message: string\): void -Prints debug logs. +## console.log -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

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

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.info - -info\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.info + +info(message: string): void Prints info-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.warn - -warn\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.warn + +warn(message: string): void Prints warn-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.error - -error\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.error + +error(message: string): void Prints error-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## Example +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## Example ``` export default { @@ -176,13 +71,11 @@ export default { var versionCode = 1; console.info('Hello World. The current version code is ' + versionCode); console.log(`versionCode: ${versionCode}`); - // The following is supported since API version 6. - console.log('versionCode:%d.', versionCode); + / / The following is supported since API version 6: console.log('versionCode:%d.', versionCode); } } ``` -Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. - -![](figures/log.png) +Switch to the HiLog window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to Info, and enter Hello World in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. +![en-us_image_0000001200913929](figures/en-us_image_0000001200913929.png) diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index ae07870d38..7fdf7692a1 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -10,7 +10,6 @@ This subsystem offers various media services covering audio and video, which pro - Audio playback ([AudioPlayer](#audioplayer)) - Video playback ([VideoPlayer](#videoplayer8)) - Audio recording ([AudioRecorder](#audiorecorder)) -- Video recording ([VideoRecorder](#videorecorder9)) The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. @@ -122,7 +121,7 @@ Creates an **AudioRecorder** instance to control audio recording. **Example** ```js -let audiorecorder = media.createAudioRecorder(); +let audiorecorder = media.createAudioRecorder(); ``` ## MediaErrorCode8+ @@ -183,13 +182,13 @@ Enumerates the media description keys. | MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number. | | MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| | MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string. | -| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms. | -| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s. | -| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel. | -| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel. | -| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps. | +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms. | +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s. | +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel. | +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel. | +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| | MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number. | -| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz. | +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz. | ## BufferingInfoType8+ @@ -197,11 +196,11 @@ Enumerates the buffering event types. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Value | Description | -| ----------------- | ---- | -------------------------- | -| BUFFERING_START | 1 | Buffering starts. | -| BUFFERING_END | 2 | Buffering ends. | -| BUFFERING_PERCENT | 3 | Buffering progress, in percent. | +| Name | Value | Description | +| ----------------- | ---- | -------------------------------- | +| BUFFERING_START | 1 | Buffering starts. | +| BUFFERING_END | 2 | Buffering ends. | +| BUFFERING_PERCENT | 3 | Buffering progress, in percent. | | CACHED_DURATION | 4 | Cache duration, in milliseconds.| ## AudioPlayer @@ -216,7 +215,7 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. | +| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | currentTime | number | Yes | No | Current audio playback position. | | duration | number | Yes | No | Audio duration. | @@ -300,8 +299,8 @@ Seeks to the specified playback position. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| **Example** @@ -478,24 +477,24 @@ Subscribes to the audio playback events. ```js let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. - console.info('audio set source success'); + console.info('audio set source success'); audioPlayer.play(); // Start the playback and trigger the 'play' event callback. }); audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); + console.info('audio play success'); audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. }); audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.info('audio pause success'); + console.info('audio pause success'); audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.info('audio reset success'); + console.info('audio reset success'); audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (typeof(seekDoneTime) == "undefined") { + if (typeof(seekDoneTime) == "undefined") { console.info('audio seek fail'); return; } @@ -503,15 +502,15 @@ audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. }); audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.info('audio volumeChange success'); + console.info('audio volumeChange success'); audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. }); audioPlayer.on('finish', () => { // Set the 'finish' event callback. - console.info('audio play finish'); + console.info('audio play finish'); audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); @@ -577,7 +576,7 @@ Subscribes to the audio playback error event. ```js audioPlayer.on('error', (error) => { // Set the error event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); @@ -610,7 +609,7 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. | +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | currentTime8+ | number | Yes | No | Current video playback position. | | duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode. | @@ -631,15 +630,15 @@ Sets **SurfaceId**. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | --------- | -------- | ---- | ------------------------- | | surfaceId | string | Yes | Surface ID to set. | -| callback | function | Yes | Callback used to set **SurfaceId**.| +| callback | function | Yes | Callback used to return the result.| **Example** ```js videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (typeof (err) == 'undefined') { - console.info('setDisplaySurface success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setDisplaySurface success!'); + } else { console.info('setDisplaySurface fail!'); } }); @@ -663,7 +662,7 @@ Sets **SurfaceId**. This API uses a promise to return the result. | Type | Description | | ------------- | ------------------------------ | -| Promise | Promise used to set **SurfaceId**.| +| Promise | Promise used to return the result.| **Example** @@ -697,9 +696,9 @@ Prepares for video playback. This API uses a callback to return the result. ```js videoPlayer.prepare((err) => { - if (typeof (err) == 'undefined') { - console.info('prepare success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('prepare success!'); + } else { console.info('prepare fail!'); } }); @@ -751,9 +750,9 @@ Starts to play video resources. This API uses a callback to return the result. ```js videoPlayer.play((err) => { - if (typeof (err) == 'undefined') { - console.info('play success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('play success!'); + } else { console.info('play fail!'); } }); @@ -805,9 +804,9 @@ Pauses video playback. This API uses a callback to return the result. ```js videoPlayer.pause((err) => { - if (typeof (err) == 'undefined') { - console.info('pause success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('pause success!'); + } else { console.info('pause fail!'); } }); @@ -859,9 +858,9 @@ Stops video playback. This API uses a callback to return the result. ```js videoPlayer.stop((err) => { - if (typeof (err) == 'undefined') { - console.info('stop success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('stop success!'); + } else { console.info('stop fail!'); } }); @@ -913,9 +912,9 @@ Switches the video resource to be played. This API uses a callback to return the ```js videoPlayer.reset((err) => { - if (typeof (err) == 'undefined') { - console.info('reset success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('reset success!'); + } else { console.info('reset fail!'); } }); @@ -959,18 +958,18 @@ Seeks to the specified playback position. The next key frame at the specified po **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| callback | function | Yes | Callback used to return the result.| +| callback | function | Yes | Callback used to return the result. | **Example** ```js videoPlayer.seek((seekTime, err) => { - if (typeof (err) == 'undefined') { - console.info('seek success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { console.info('seek fail!'); } }); @@ -986,19 +985,19 @@ Seeks to the specified playback position. This API uses a callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | function | Yes | Callback used to return the result.| +| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | +| callback | function | Yes | Callback used to return the result. | **Example** ```js videoPlayer.seek((seekTime, seekMode, err) => { - if (typeof (err) == 'undefined') { - console.info('seek success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { console.info('seek fail!'); } }); @@ -1014,10 +1013,10 @@ Seeks to the specified playback position. If **mode** is not specified, the next **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------- | ---- | ------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | No | Seek mode. | +| mode | [SeekMode](#seekmode8) | No | Seek mode. | **Return value** @@ -1062,9 +1061,9 @@ Sets the volume. This API uses a callback to return the result. ```js videoPlayer.setVolume((vol, err) => { - if (typeof (err) == 'undefined') { - console.info('setVolume success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setVolume success!'); + } else { console.info('setVolume fail!'); } }); @@ -1122,9 +1121,9 @@ Releases the video playback resource. This API uses a callback to return the res ```js videoPlayer.release((err) => { - if (typeof (err) == 'undefined') { - console.info('release success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('release success!'); + } else { console.info('release fail!'); } }); @@ -1257,9 +1256,9 @@ Sets the video playback speed. This API uses a callback to return the result. ```js videoPlayer.setSpeed((speed:number, err) => { - if (typeof (err) == 'undefined') { - console.info('setSpeed success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setSpeed success!'); + } else { console.info('setSpeed fail!'); } }); @@ -1318,7 +1317,7 @@ Subscribes to the video playback completion event. ```js videoPlayer.on('playbackCompleted', () => { - console.info('playbackCompleted success!'); + console.info('playbackCompleted success!'); }); ``` @@ -1365,7 +1364,7 @@ Subscribes to the frame rendering start event. ```js videoPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success!'); + console.info('startRenderFrame success!'); }); ``` @@ -1412,7 +1411,7 @@ Subscribes to the video playback error event. ```js videoPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`video error called, errName is ${error.name}`); // Print the error name. + console.info(`video error called, errName is ${error.name}`); // Print the error name. console.info(`video error called, errCode is ${error.code}`); // Print the error code. console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); @@ -1656,7 +1655,7 @@ Subscribes to the audio recording events. **Example** ```js -let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. +let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { audioEncoder : media.AudioEncoder.AAC_LC, , audioEncodeBitRate : 22050, @@ -1666,34 +1665,34 @@ let audioRecorderConfig = { uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); -audioRecorder.on('start', () => { // Set the 'start' event callback. +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the 'pause' event callback. +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the 'resume' event callback. +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the 'stop' event callback. +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the 'release' event callback. +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the 'reset' event callback. +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` ### on('error') @@ -1714,12 +1713,12 @@ Subscribes to the audio recording error event. **Example** ```js -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig @@ -1736,11 +1735,14 @@ Describes audio recording configurations. | numberOfChannels | number | No | Number of audio channels. The default value is **2**. | | format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | | location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| | audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | -## AudioEncoder +## AudioEncoder(deprecated) + +> **NOTE** +> This API is deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. Enumerates the audio encoding formats. @@ -1748,14 +1750,17 @@ Enumerates the audio encoding formats. | Name | Default Value| Description | | ------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default audio encoding format, which is Adaptive Multi Rate-Narrow Band Speech Codec (AMR-NB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_NB | 1 | AMR-NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet.| +| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| | AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| -## AudioOutputFormat +## AudioOutputFormat(deprecated) + +> **NOTE** +> This API is deprecated since API version 8. You are advised to use [ContainerFormatType ](#containerformattype8) instead. Enumerates the audio output formats. @@ -1763,10 +1768,10 @@ Enumerates the audio output formats. | Name | Default Value| Description | | -------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encapsulation format, which is MPEG-4.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet.| | MPEG_4 | 2 | MPEG-4. | -| AMR_NB | 3 | AMR_NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_WB | 4 | AMR_WB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet.| +| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet.| | AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| ## ContainerFormatType8+ @@ -1777,7 +1782,7 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MP4.| +| CFT_MPEG_4 | "mp4" | Video container format MPEG-4 .| | CFT_MPEG_4A | "m4a" | Audio container format M4A.| ## Location diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index b741802e7e..e113626278 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -5,22 +5,22 @@ ## Modules to Import ``` -import mediaLibrary from '@ohos.multimedia.medialibrary'; +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; ``` -## mediaLibrary.getMediaLibrary +## mediaLibrary.getMediaLibrary8+ getMediaLibrary(context: Context): MediaLibrary -Obtains a **MediaLibrary** instance, which is used to access and modify personal data of users. +Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Context of the ability. This parameter is optional for API version 7 and earlier versions, but mandatory for API version 8 and later versions.| +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| context | Context | Yes | Context of the ability.| **Return value** @@ -36,9 +36,31 @@ import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() var media = mediaLibrary.getMediaLibrary(context); ``` +## mediaLibrary.getMediaLibrary + +getMediaLibrary(): MediaLibrary + +Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. + +> **Note**: This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Return value** + +| Type | Description | +| ----------------------------- | :--------- | +| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| + +**Example** + +```js +var media = mediaLibrary.getMediaLibrary(); +``` + ## MediaLibrary -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void @@ -51,10 +73,10 @@ Obtains file assets (also called files). This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult8)> | Yes | Asynchronous callback of **FetchFileResult**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | --------------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Asynchronous callback of **FetchFileResult**.| **Example** @@ -76,7 +98,7 @@ mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { } }); ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> @@ -88,15 +110,15 @@ Obtains file assets. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------ | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files.| **Return value** -| Type | Description | -| ------------------------------------ | ------- | -| [FetchFileResult](#fetchfileresult8) | Result set of the file retrieval operation.| +| Type | Description | +| ------------------------------------ | -------------- | +| [FetchFileResult](#fetchfileresult7) | Result set of the file retrieval operation.| **Example** @@ -171,12 +193,12 @@ Creates a media asset. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | --------------------------------------- | ---- | ---------------------------------------- | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | Display file name. | -| relativePath | string | Yes | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.| -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Asynchronous callback for **FileAsset**. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype8) | Yes | Media type. | +| displayName | string | Yes | Display file name. | +| relativePath | string | Yes | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.| +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Asynchronous callback for **FileAsset**. | **Example** @@ -208,17 +230,17 @@ Creates a media asset. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ----------------------- | ---- | ---------------------------------------- | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | Display file name. | -| relativePath | string | Yes | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.| +| Name | Type | Mandatory| Description | +| ------------ | ------------------------ | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype8) | Yes | Media type. | +| displayName | string | Yes | Display file name. | +| relativePath | string | Yes | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.| **Return value** -| Type | Description | -| ------------------------ | ------------- | -| [FileAsset](#fileasset8) | Media data (FileAsset).| +| Type | Description | +| ------------------------ | ----------------- | +| [FileAsset](#fileasset7) | Media data (FileAsset).| **Example** @@ -246,10 +268,10 @@ Obtains a public directory. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------- | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | -| callback | AsyncCallback<string> | Yes | Callback used to return the public directory.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------- | +| type | [DirectoryType](#directorytype8) | Yes | Type of the public directory. | +| callback | AsyncCallback<string> | Yes | Callback used to return the public directory.| **Example** @@ -274,15 +296,15 @@ Obtains a public directory. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------------------------------- | ---- | ------ | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ------------ | +| type | [DirectoryType](#directorytype8) | Yes | Type of the public directory.| **Return value** -| Type | Description | -| --------------- | -------- | -| Promise | Promise used to return the public directory.| +| Type | Description | +| ---------------- | ---------------- | +| Promise\ | Promise used to return the public directory.| **Example** @@ -298,7 +320,7 @@ async function example() { } ``` -### getAlbums8+ +### getAlbums7+ getAlbums(options: MediaFetchOptions, callback: AsyncCallback): void @@ -310,10 +332,10 @@ Obtains the albums. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------- | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the albums. | -| callback | AsyncCallback<Array<[Album](#album8)>> | Yes | Callback used to return the albums.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | --------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<Array<[Album](#album7)>> | Yes | Callback used to return the albums.| **Example** @@ -333,7 +355,7 @@ mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { }) ``` -### getAlbums8+ +### getAlbums7+ getAlbums(options: MediaFetchOptions): Promise @@ -345,15 +367,15 @@ Obtains the albums. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the albums.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------ | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the albums.| **Return value** -| Type | Description | -| -------------------------------- | --------- | -| Promise> | Promise used to return the albums.| +| Type | Description | +| -------------------------------- | ------------- | +| Promise> | Promise used to return the albums.| **Example** @@ -690,7 +712,7 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { ``` -## FileAsset8+ +## FileAsset7+ Provides APIs for encapsulating file asset attributes. @@ -698,29 +720,29 @@ Provides APIs for encapsulating file asset attributes. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Description | -| ------------ | ----------------------- | ---- | ---- | --------------------------------------- | -| id | number | Yes | No | File asset ID. | -| uri | string | Yes | No | File asset URI, for example, dataability:///media/image/2.| -| mimeType | string | Yes | No | Extended file attributes. | -| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | -| displayName | string | Yes | Yes | Display file name, including the file name extension. | -| title | string | Yes | Yes | Title in the file. | -| relativePath | string | Yes | Yes | Relative public directory of the file. | -| parent | number | Yes | No | Parent directory ID. | -| size | number | Yes | No | File size, in bytes. | -| dateAdded | number | Yes | No | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| dateModified | number | Yes | No | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| dateTaken | number | Yes | No | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | -| artist | string | Yes | No | Artist of the file. | -| audioAlbum | string | Yes | No | Audio album. | -| width | number | Yes | No | Image width, in pixels. | -| height | number | Yes | No | Image height, in pixels. | -| orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees). | -| duration | number | Yes | No | Duration, in seconds. | -| albumId | number | Yes | No | ID of the album to which the file belongs. | -| albumUri | string | Yes | No | URI of the album to which the file belongs. | -| albumName | string | Yes | No | Name of the album to which the file belongs. | +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | +| id | number | Yes | No | File asset ID. | +| uri | string | Yes | No | File asset URI, for example, dataability:///media/image/2. | +| mimeType | string | Yes | No | Extended file attributes. | +| mediaType8+ | [MediaType](#mediatype8) | Yes | No | Media type. | +| displayName | string | Yes | Yes | Display file name, including the file name extension. | +| title | string | Yes | Yes | Title in the file. | +| relativePath8+ | string | Yes | Yes | Relative public directory of the file. | +| parent8+ | number | Yes | No | Parent directory ID. | +| size | number | Yes | No | File size, in bytes. | +| dateAdded | number | Yes | No | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | +| dateModified | number | Yes | No | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | +| dateTaken | number | Yes | No | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| artist8+ | string | Yes | No | Artist of the file. | +| audioAlbum8+ | string | Yes | No | Audio album. | +| width | number | Yes | No | Image width, in pixels. | +| height | number | Yes | No | Image height, in pixels. | +| orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).| +| duration8+ | number | Yes | No | Duration, in seconds. | +| albumId | number | Yes | No | ID of the album to which the file belongs. | +| albumUri8+ | string | Yes | No | URI of the album to which the file belongs. | +| albumName | string | Yes | No | Name of the album to which the file belongs. | ### isDirectory8+ @@ -946,7 +968,7 @@ close(fd: number, callback: AsyncCallback<void>): void Closes this file asset. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA ('r' enabled) and ohos.permission.WRITE_MEDIA ('w' enabled) +**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -987,7 +1009,7 @@ close(fd: number): Promise<void> Closes this file asset. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA ('r' enabled) and ohos.permission.WRITE_MEDIA ('w' enabled) +**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1127,15 +1149,19 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A async function example() { let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size, (err, pixelmap) => { + asset.getThumbnail(size) + .then((pixelmap) => { console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }) + .catch((err) => { + console.info('mediaLibraryTest : getThumbnail fail'+ err); }); } ``` @@ -1460,11 +1486,11 @@ async function example() { } ``` -## FetchFileResult8+ +## FetchFileResult7+ Implements the result set of the file retrieval operation. -### getCount8+ +### getCount7+ getCount(): number @@ -1493,7 +1519,7 @@ async function example() { } ``` -### isAfterLast8+ +### isAfterLast7+ isAfterLast(): boolean @@ -1536,7 +1562,7 @@ async function example() { } ``` -### close8+ +### close7+ close(): void @@ -1560,7 +1586,7 @@ async function example() { } ``` -### getFirstObject8+ +### getFirstObject7+ getFirstObject(callback: AsyncCallback<FileAsset>): void @@ -1570,9 +1596,9 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the first file asset.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the first file asset.| **Example** @@ -1596,7 +1622,7 @@ async function example() { } ``` -### getFirstObject8+ +### getFirstObject7+ getFirstObject(): Promise<FileAsset> @@ -1606,9 +1632,9 @@ Obtains the first file asset in the result set. This API uses a promise to retur **Return value** -| Type | Description | -| --------------------------------------- | -------------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the file asset.| +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the file asset.| **Example** @@ -1630,7 +1656,7 @@ async function example() { } ``` -### getNextObject8+ +### getNextObject7+ getNextObject(callback: AsyncCallback<FileAsset>): void @@ -1642,9 +1668,9 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | ------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the next file asset.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ----------------------------------------- | +| callbacke | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the next file asset.| **Example** @@ -1668,7 +1694,7 @@ async function example() { } ``` -### getNextObject8+ +### getNextObject7+ getNextObject(): Promise<FileAsset> @@ -1680,9 +1706,9 @@ Obtains the next file asset in the result set. This API uses a promise to return **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1702,7 +1728,7 @@ async function example() { } ``` -### getLastObject8+ +### getLastObject7+ getLastObject(callback: AsyncCallback<FileAsset>): void @@ -1712,9 +1738,9 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the last file asset.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.| **Example** @@ -1738,7 +1764,7 @@ async function example() { } ``` -### getLastObject8+ +### getLastObject7+ getLastObject(): Promise<FileAsset> @@ -1748,9 +1774,9 @@ Obtains the last file asset in the result set. This API uses a promise to return **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1768,7 +1794,7 @@ async function example() { } ``` -### getPositionObject8+ +### getPositionObject7+ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void @@ -1781,7 +1807,7 @@ Obtains a file asset with the specified index in the result set. This API uses a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------ | | index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the last file asset.| +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.| **Example** @@ -1805,7 +1831,7 @@ async function example() { } ``` -### getPositionObject8+ +### getPositionObject7+ getPositionObject(index: number): Promise<FileAsset> @@ -1823,9 +1849,9 @@ Obtains a file asset with the specified index in the result set. This API uses a **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1849,7 +1875,7 @@ async function example() { } ``` -### getAllObject8+ +### getAllObject7+ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void @@ -1863,7 +1889,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the file assets.| +| callback | AsyncCallback> | Yes | Callback used to return the file assets.| **Example** @@ -1887,7 +1913,7 @@ async function example() { } ``` -### getAllObject8+ +### getAllObject7+ getAllObject(): Promise<Array<FileAsset>> @@ -1897,9 +1923,9 @@ Obtains all the file assets in the result set. This API uses a promise to return **Return value** -| Type | Description | -| ---------------------------------------- | --------------- | -| Promise> | Promise used to return the file assets.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise> | Promise used to return the file assets.| **Example** @@ -1917,7 +1943,7 @@ async function example() { } ``` -## Album8+ +## Album7+ Provides APIs to implement a physical album. @@ -1927,13 +1953,13 @@ Provides APIs to implement a physical album. | Name | Type | Readable | Writable | Description | | ------------ | ------ | ---- | ---- | ------- | -| albumId | number | Yes | No | Album ID. | -| albumName | string | Yes | Yes | Album name. | -| albumUri | string | Yes | No | Album URI. | +| albumId | number | Yes | No | Album ID. | +| albumName | string | Yes | Yes | Album name. | +| albumUri8+ | string | Yes | No | Album URI. | | dateModified | number | Yes | No | Date when the album was modified. | -| count | number | Yes | No | Number of files in the album.| -| relativePath | string | Yes | No | Relative path of the album. | -| coverUri | string | Yes | No | URI of the cover file of the album.| +| count8+ | number | Yes | No | Number of files in the album.| +| relativePath8+ | string | Yes | No | Relative path of the album. | +| coverUri8+ | string | Yes | No | URI of the cover file of the album.| ### commitModify8+ @@ -1947,9 +1973,9 @@ Commits the modification of the album attributes to the database. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----- | -| callback | AsyncCallback<void> | Yes | Void callback.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Void callback.| **Example** @@ -2007,7 +2033,7 @@ async function example() { } ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void @@ -2019,10 +2045,10 @@ Obtains the file assets in this album. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult8)> | Yes | Callback used to return the file assets.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.| **Example** @@ -2041,7 +2067,7 @@ async function example() { } ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options?: MediaFetchOptions): Promise<FetchFileResult> @@ -2053,15 +2079,15 @@ Obtains the file assets in this album. This API uses a promise to return the res **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | No | Options for fetching the files.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | No | Options for fetching the files.| **Return value** -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[FetchFileResult](#fetchfileresult8)> | Promise used to return the file assets.| +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult7)> | Promise used to return the file assets.| **Example** @@ -2087,105 +2113,101 @@ Describes information about a registered device. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Description | -| ---------- | ---------- | ---- | ---- | --------- | -| deviceName | string | Yes | No | Name of the registered device. | -| networkId | string | Yes | No | Network ID of the registered device.| -| deviceType | DeviceType | Yes | No | Type of the registered device. | -| isOnline | boolean | Yes | No | Whether the registered device is online. | +| Name | Type | Readable| Writable| Description | +| ---------- | -------------------------- | ---- | ---- | ---------------- | +| deviceName | string | Yes | No | Name of the registered device. | +| networkId | string | Yes | No | Network ID of the registered device.| +| deviceType | [DeviceType](#devicetype8) | Yes | No | Type of the registered device. | +| isOnline | boolean | Yes | No | Whether the registered device is online. | -MediaType ---------- +## MediaType8+ Enumerates media types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ----- | ---- | ---- | -| FILE | 0 | File. | -| IMAGE | 1 | Image. | -| VIDEO | 2 | Video. | -| AUDIO | 3 | Audio. | +| Name | Default Value| Description| +| ----- | ------ | ---- | +| FILE | 1 | File.| +| IMAGE | 3 | Image.| +| VIDEO | 4 | Video.| +| AUDIO | 5 | Audio.| -FileKey -------- +## FileKey8+ Enumerates key file information. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------- | ------------------- | -------------------------------- | -| ID | file_id | File ID. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | Display file name. | -| PARENT | parent | Parent directory ID. | -| MIME_TYPE | mime_type | Extended file attributes. | -| MEDIA_TYPE | media_type | Media type. | -| SIZE | size | File size, in bytes. | -| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | -| TITLE | title | Title in the file. | -| ARTIST | artist | Artist of the file. | -| AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in seconds. | -| WIDTH | width | Image width, in pixels. | -| HEIGHT | height | Image height, in pixels. | +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| ID | file_id | File ID. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | Display file name. | +| PARENT | parent | Parent directory ID. | +| MIME_TYPE | mime_type | Extended file attributes. | +| MEDIA_TYPE | media_type | Media type. | +| SIZE | size | File size, in bytes. | +| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| TITLE | title | Title in the file. | +| ARTIST | artist | Artist of the file. | +| AUDIOALBUM | audio_album | Audio album. | +| DURATION | duration | Duration, in seconds. | +| WIDTH | width | Image width, in pixels. | +| HEIGHT | height | Image height, in pixels. | | ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| -| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | -| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | +| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | +| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | -DirectoryType -------------- +## DirectoryType8+ Enumerates directory types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------- | ---- | ------------ | -| DIR_CAMERA | 0 | Directory of camera files.| -| DIR_VIDEO | 1 | Directory of video files. | -| DIR_IMAGE | 2 | Directory of image files. | -| DIR_AUDIO | 3 | Directory of audio files. | -| DIR_DOCUMENTS | 4 | Directory of documents. | -| DIR_DOWNLOAD | 5 | Download directory. | +| Name | Default Value| Description | +| ------------- | ------ | ------------------ | +| DIR_CAMERA | 0 | Directory of camera files.| +| DIR_VIDEO | 1 | Directory of video files. | +| DIR_IMAGE | 2 | Directory of image files. | +| DIR_AUDIO | 3 | Directory of audio files. | +| DIR_DOCUMENTS | 4 | Directory of documents. | +| DIR_DOWNLOAD | 5 | Download directory. | -DeviceType ------------ +## DeviceType8+ Enumerates device types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------ | ---- | ----- | -| TYPE_UNKNOWN | 0 | Unknown.| -| TYPE_LAPTOP | 1 | Laptop.| -| TYPE_PHONE | 2 | Phone. | -| TYPE_TABLET | 3 | Tablet. | -| TYPE_WATCH | 4 | Smart watch. | -| TYPE_CAR | 5 | Vehicle-mounted device. | -| TYPE_TV | 6 | TV. | +| Name | Default Value| Description | +| ------------ | ------ | ---------- | +| TYPE_UNKNOWN | 0 | Unknown.| +| TYPE_LAPTOP | 1 | Laptop.| +| TYPE_PHONE | 2 | Phone. | +| TYPE_TABLET | 3 | Tablet. | +| TYPE_WATCH | 4 | Smart watch. | +| TYPE_CAR | 5 | Vehicle-mounted device. | +| TYPE_TV | 6 | TV. | -## MediaFetchOptions8+ +## MediaFetchOptions7+ Describes options for fetching media files. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Mandatory | Description | -| ------------- | ------------------- | ---- | ---- | ---- | ---------------------------------------- | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| -| selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| -| uri | string | Yes | Yes | No | File URI. | -| networkId | string | Yes | Yes | No | Network ID of the registered device. | -| extendArgs | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | +| Name | Type | Readable| Writable| Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| +| selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | +| order8+ | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| +| uri8+ | string | Yes | Yes | No | File URI. | +| networkId8+ | string | Yes | Yes | No | Network ID of the registered device. | +| extendArgs8+ | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | ## Size8+ diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md new file mode 100644 index 0000000000..7cb3263efc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -0,0 +1,145 @@ +# Media Query + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**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 + +``` +import mediaquery from '@ohos.mediaquery' +``` + + +## Required Permissions + +None. + + +## mediaquery.matchMediaSync + +matchMediaSync(condition: string): MediaQueryListener + +Sets the media query criteria and returns the corresponding listening handle. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | condition | string | Yes| Matching condition of a media event.| + +- Return value + | Type| Description| + | -------- | -------- | + | MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| + +- Example + ``` + listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + ``` + + +## MediaQueryListener + +Media query handle, including the first query result when the handle is applied for. + + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| matches | boolean | Yes| No| Whether the match condition is met.| +| media | string | Yes| No| Matching condition of a media event.| + + +### on + +on(type: 'change', callback: Callback<MediaQueryResult>): void + +Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Must enter the string **change**.| + | callback | Callback<MediaQueryResult> | Yes| Callback registered with media query.| + +- Example + For details, see [off Example](#off). + + +### off + +off(type: 'change', callback?: Callback<MediaQueryResult>): void + +Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | boolean | Yes| Must enter the string **change**.| + | callback | Callback<MediaQueryResult> | No| Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| + +- Example + ``` + import mediaquery from '@ohos.mediaquery' + + listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + function onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + // do something here + } else { + // do something here + } + } + this.listener.on('change', this.onPortrait) // Registration callback. + this.listener.off('change', this.onPortrait) // Deregistration callback. + ``` + + +## MediaQueryResult + + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| matches | boolean | Yes| No| Whether the match condition is met.| +| media | string | Yes| No| Matching condition of a media event.| + + +### Example + +``` +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' + } + } + + aboutToAppear() { + portraitFunc = this.onPortrait.bind(this) //bind current js instance + this.listener.on('change', portraitFunc) + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.text).fontSize(24).fontColor(this.color) + } + .width('100%').height('100%') + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 05cd497014..a36fc053da 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -1,8 +1,8 @@ # missionManager -> **NOTE** -> The initial APIs of this module are supported since API version 8. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Provides mission management. You can use the APIs to lock, unlock, and clear missions, and switch a mission to the foreground. @@ -18,7 +18,7 @@ import missionManager from '@ohos.application.missionManager' ## missionManager.registerMissionListener -function registerMissionListener(listener: MissionListener): number; +registerMissionListener(listener: MissionListener): number; Registers a listener to observe the mission status. @@ -53,7 +53,7 @@ Registers a listener to observe the mission status. ## missionManager.unregisterMissionListener -function unregisterMissionListener(listenerId: number, callback: AsyncCallback<void>): void; +unregisterMissionListener(listenerId: number, callback: AsyncCallback<void>): void; Unregisters a mission status listener. This API uses an asynchronous callback to return the result. @@ -86,7 +86,7 @@ Unregisters a mission status listener. This API uses an asynchronous callback to ## missionManager.unregisterMissionListener -function unregisterMissionListener(listenerId: number): Promise<void>; +unregisterMissionListener(listenerId: number): Promise<void>; Unregisters a mission status listener. This API uses a promise to return the result. @@ -98,6 +98,12 @@ Unregisters a mission status listener. This API uses a promise to return the res | -------- | -------- | -------- | -------- | | listenerId | number | Yes| Index of the mission status listener to unregister. Each listener has a unique index, which is returned by **registerMissionListener**.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js @@ -110,7 +116,7 @@ Unregisters a mission status listener. This API uses a promise to return the res console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - await missionManager.unregisterMissionListener(listenerid).catch(function (err){ + missionManager.unregisterMissionListener(listenerid).catch(function (err){ console.log(err); }); ``` @@ -118,7 +124,7 @@ Unregisters a mission status listener. This API uses a promise to return the res ## missionManager.getMissionInfo -function getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; +getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; Obtains the information of a given mission. This API uses an asynchronous callback to return the result. @@ -130,7 +136,7 @@ Obtains the information of a given mission. This API uses an asynchronous callba | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<MissionInfo> | Yes| Callback used to return the mission information obtained.| + | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| **Example** @@ -145,13 +151,13 @@ Obtains the information of a given mission. This API uses an asynchronous callba console.log("mission.timestamp = " + mission.timestamp); console.log("mission.label = " + mission.label); console.log("mission.iconPath = " + mission.iconPath); - } + }); ``` ## missionManager.getMissionInfo -function getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; +getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; Obtains the information of a given mission. This API uses a promise to return the result. @@ -168,14 +174,14 @@ Obtains the information of a given mission. This API uses a promise to return th | Type| Description| | -------- | -------- | - | [MissionInfo](js-apis-application-MissionInfo.md) | Promise used to return the mission information obtained.| + | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var mission = await missionManager.getMissionInfo("", id).catch(function (err){ + var mission = missionManager.getMissionInfo("", id).catch(function (err){ console.log(err); }); ``` @@ -183,7 +189,7 @@ Obtains the information of a given mission. This API uses a promise to return th ## missionManager.getMissionInfos -function getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; +getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; Obtains information of all missions. This API uses an asynchronous callback to return the result. @@ -195,7 +201,7 @@ Obtains information of all missions. This API uses an asynchronous callback to r | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | numMax | number | Yes| Maximum number of missions whose information can be obtained.| - | callback | AsyncCallback<Array<[MissionInfo](js-apis-application-MissionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| + | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| **Example** @@ -212,7 +218,7 @@ Obtains information of all missions. This API uses an asynchronous callback to r ## missionManager.getMissionInfos -function getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; +getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; Obtains information of all missions. This API uses a promise to return the result. @@ -229,14 +235,14 @@ Obtains information of all missions. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Array<MissionInfo> | Promise used to return the array of mission information obtained.| + | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); ``` @@ -244,7 +250,7 @@ Obtains information of all missions. This API uses a promise to return the resul ## missionManager.getMissionSnapShot -function getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; +getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. @@ -279,7 +285,7 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback ## missionManager.getMissionSnapShot -function getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; +getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; Obtains the snapshot of a given mission. This API uses a promise to return the result. @@ -296,20 +302,20 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Type| Description| | -------- | -------- | - | MissionSnapshot | Promise used to return the snapshot information obtained.| + | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - var snapshot = await missionManager.getMissionSnapShot("", id).catch(function (err){ + var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ console.log(err); }); ``` @@ -317,7 +323,7 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r ## missionManager.lockMission -function lockMission(missionId: number, callback: AsyncCallback<void>): void; +lockMission(missionId: number, callback: AsyncCallback<void>): void; Locks a given mission. This API uses an asynchronous callback to return the result. @@ -350,7 +356,7 @@ Locks a given mission. This API uses an asynchronous callback to return the resu ## missionManager.lockMission -function lockMission(missionId: number): Promise<void>; +lockMission(missionId: number): Promise<void>; Locks a given mission. This API uses a promise to return the result. @@ -362,19 +368,25 @@ Locks a given mission. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.lockMission(id).catch(function (err){ + missionManager.lockMission(id).catch(function (err){ console.log(err); }); ``` @@ -382,7 +394,7 @@ Locks a given mission. This API uses a promise to return the result. ## missionManager.unlockMission -function unlockMission(missionId: number, callback: AsyncCallback<void>): void; +unlockMission(missionId: number, callback: AsyncCallback<void>): void; Unlocks a given mission. This API uses an asynchronous callback to return the result. @@ -390,9 +402,10 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -414,7 +427,7 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re ## missionManager.unlockMission -function unlockMission(missionId: number): Promise<void>; +unlockMission(missionId: number): Promise<void>; Unlocks a given mission. This API uses a promise to return the result. @@ -426,22 +439,28 @@ Unlocks a given mission. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.lockMission(id).catch(function (err){ + missionManager.lockMission(id).catch(function (err){ console.log(err); }); - await missionManager.unlockMission(id).catch(function (err){ + missionManager.unlockMission(id).catch(function (err){ console.log(err); }); ``` @@ -449,7 +468,7 @@ Unlocks a given mission. This API uses a promise to return the result. ## missionManager.clearMission -function clearMission(missionId: number, callback: AsyncCallback<void>): void; +clearMission(missionId: number, callback: AsyncCallback<void>): void; Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. @@ -482,7 +501,7 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy ## missionManager.clearMission -function clearMission(missionId: number): Promise<void>; +clearMission(missionId: number): Promise<void>; Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. @@ -494,19 +513,25 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.clearMission(id).catch(function (err){ + missionManager.clearMission(id).catch(function (err){ console.log(err); }); ``` @@ -514,7 +539,7 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom ## missionManager.clearAllMissions -function clearAllMissions(callback: AsyncCallback<void>): void; +clearAllMissions(callback: AsyncCallback<void>): void; Clears all unlocked missions. This API uses an asynchronous callback to return the result. @@ -533,17 +558,23 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t ## missionManager.clearAllMissions -function clearAllMissions(): Promise<void>; +clearAllMissions(): Promise<void>; Clears all unlocked missions. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - await missionManager.clearAllMissions().catch(function (err){ + missionManager.clearAllMissions().catch(function (err){ console.log(err); }); ``` @@ -551,7 +582,7 @@ Clears all unlocked missions. This API uses a promise to return the result. ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; +moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. @@ -584,7 +615,7 @@ Switches a given mission to the foreground. This API uses an asynchronous callba ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; +moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; Switches a given mission to the foreground, with the startup parameters for the switch specified, such as the window mode and device ID. This API uses an asynchronous callback to return the result. @@ -618,9 +649,9 @@ Switches a given mission to the foreground, with the startup parameters for the ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; +moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; -Switches a given mission to the foreground. This API uses a promise to return the result. +Switches a given mission to the foreground, with the startup parameters for the switch specified, such as the window mode and device ID. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -631,19 +662,42 @@ Switches a given mission to the foreground. This API uses a promise to return th | missionId | number | Yes| Mission ID.| | options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.moveMissionToFront(id).catch(function (err){ + missionManager.moveMissionToFront(id).catch(function (err){ console.log(err); }); ``` + +## MissionInfo + +Describes the mission information. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-featureAbility.md#want) | Yes| Yes| **Want** information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission is continuable.| 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 c0d9c297f7..bd4404ebc0 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -684,83 +684,14 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | ------ | ------ | ------------------------- | | netId | number | Network ID. The value must be greater than or equal to 100.| -### bindSocket - -bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback<void>): void - -Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | ---------------- | -| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - -``` -// Bind the TCPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let tcpSocket = socket.constructTCPSocketInstance() - netHandle.bindSocket(tcpSocket, (function (error) { - console.log(JSON.stringify(error)) - })) -}) -// Bind the UDPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let udpSocket = socket.constructUDPSocketInstance() - netHandle.bindSocket(udpSocket, (function (error) { - console.log(JSON.stringify(error)) - })) -}) -``` - - -### bindSocket - -bindSocket(socketParam: TCPSocket | UDPSocket): Promise<void> - -Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| - -**Return Value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -``` -// Bind the TCPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let tcpSocket = socket.constructTCPSocketInstance() - netHandle.bindSocket(tcpSocket).then(function () { - console.log("bind socket success") - }) -}) -// Bind the UDPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let udpSocket = socket.constructUDPSocketInstance() - netHandle.bindSocket(udpSocket).then(function () { - console.log("bind socket success") - }) -}) -``` - ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -788,6 +719,8 @@ getAddressesByName(host: string): Promise\> Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -819,6 +752,8 @@ getAddressByName(host: string, callback: AsyncCallback\): void Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -846,6 +781,8 @@ getAddressByName(host: string): Promise\ Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -893,7 +830,7 @@ Defines the network capability set. | linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.| | linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.| | networkCap | Array<[NetCap](#netcap)> | Network capability. | -| bearerTypes | Array<[NetBearType](#netbearType)> | Network type. | +| bearerTypes | Array<[NetBearType](#netbeartype)> | Network type. | ## NetCap @@ -971,4 +908,4 @@ Defines the network address. | ------- | ------ | ------------------------------ | | address | string | Network address. | | family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | Port number. The value ranges from **0** to **65535**. | +| port | number | Port number. The value ranges from **0** to **65535**. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 14f043f8b3..2760d6c9cb 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,10 +1,7 @@ -# Notification Module - - -## Required Permissions - -None +# Notification +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,152 +9,22 @@ None import Notification from '@ohos.notification'; ``` -## System Capabilities - -```js -SystemCapability.Notification.Notification -``` - -## Notification.publish(request: NotificationRequest, callback: AsyncCallback\) - -- Functionality - - Publishes a notification. This method uses a callback to return the result. - -- Parameters - - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------------------------- | -| request | Read-only| NotificationRequest | Yes| Notification to publish.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| - -- NotificationRequest - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------------- | -------- | --------------------------------------------- | ---- | -------------------------- | -| content | Readable and writable| NotificationContent | Yes| Notification content.| -| id | Readable and writable| number | No| Notification ID.| -| slotType | Readable and writable| SlotType | No| Notification slot type.| -| isOngoing | Readable and writable| boolean | No| Whether the notification is an ongoing notification.| -| isUnremovable | Readable and writable| boolean | No| Whether the notification can be removed.| -| deliveryTime | Readable and writable| number | No| Time when the notification is sent.| -| tapDismissed | Readable and writable| boolean | No| Whether the notification can be automatically cleared.| -| autoDeletedTime | Readable and writable| number | No| Time when the notification is automatically cleared.| -| wantAgent | Readable and writable| WantAgent | No| **WantAgent** object to which the notification will be redirected after being clicked.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extended parameter.| -| color | Readable and writable| number | No| Background color of the notification.| -| colorEnabled | Readable and writable| boolean | No| Whether the notification background color is enabled.| -| isAlertOnce | Readable and writable| boolean | No| Whether the notification triggers an alert only once.| -| isStopwatch | Readable and writable| boolean | No| Whether to display the stopwatch.| -| isCountDown | Readable and writable| boolean | No| Whether to display the countdown time.| -| isFloatingIcon | Readable and writable| boolean | No| Whether the notification is displayed as a floating icon.| -| label | Readable and writable| string | No| Notification label.| -| badgeIconStyle | Readable and writable| number | No| Notification badge type.| -| showDeliveryTime | Readable and writable| boolean | No| Whether to display the time when the notification is delivered.| -| actionButtons | Readable and writable| Array\ | No| Buttons in the notification. Up to two buttons are allowed.| -| smallIcon | Readable and writable| PixelMap | No| Small notification icon.| -| largeIcon | Readable and writable| PixelMap | No| Large notification icon.| -| creatorBundleName | Read-only| string | No| Name of the bundle that creates the notification.| -| creatorUid | Read-only| number | No| UID of the notification creator.| -| creatorPid | Read-only| number | No| PID of the notification creator.| -| hashCode | Read-only| string | No| Unique ID of the notification.| -| classification | Readable and writable| string | No| Notification category.| -| groupName | Readable and writable| string | No| Notification group name.| -| template8+ | Readable and writable| [NotificationTemplate](#notificationtemplate) | No| Notification template.| - -NotificationContent +## Notification.publish -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | ---------------------------- | ---- | ------------------ | -| contentType | Readable and writable| ContentType | Yes| Notification content type.| -| normal | Readable and writable| NotificationBasicContent | No| Normal text.| -| longText | Readable and writable| NotificationLongTextContent | No| Long text.| -| multiLine | Readable and writable| NotificationMultiLineContent | No| Multi-line text.| -| picture | Readable and writable| NotificationPictureContent | No| Picture-attached.| +publish(request: NotificationRequest, callback: AsyncCallback\): void -- ContentType +Publishes a notification. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Description| -| --------------------------------- | -------- | ----------- | ---------------- | -| NOTIFICATION_CONTENT_BASIC_TEXT | Read-only| ContentType | Normal text notification.| -| NOTIFICATION_CONTENT_LONG_TEXT | Read-only| ContentType | Long text notification.| -| NOTIFICATION_CONTENT_PICTURE | Read-only| ContentType | Picture-attached notification.| -| NOTIFICATION_CONTENT_CONVERSATION | Read-only| ContentType | Conversation notification.| -| NOTIFICATION_CONTENT_MULTILINE | Read-only| ContentType | Multi-line text notification.| +**System capability**: SystemCapability.Notification.Notification -- NotificationBasicContent +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------ | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | -- NotificationLongTextContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------ | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| longText | Readable and writable| string | Yes| Long text content of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| - -- NotificationMultiLineContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | --------------- | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| longTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| -| lines | Readable and writable| Array\ | Yes| Multi-line content.| - -- NotificationPictureContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | -------------- | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| -| picture | Readable and writable| image.PixelMap | Yes| Picture included in the notification.| - -- SlotType - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------------- | -------- | -------- | ---- | -------- | -| SOCIAL_COMMUNICATION | Read-only| SlotType | No| Notification slot for social communication.| -| SERVICE_INFORMATION | Read-only| SlotType | No| Notification slot for service information.| -| CONTENT_INFORMATION | Read-only| SlotType | No| Notification slot for content consultation.| -| OTHER_TYPES | Read-only| SlotType | No| Notification slot for other purposes.| - -- NotificationActionButton - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ------------------------- | -| title | Readable and writable| string | Yes| Button title.| -| wantAgent | Readable and writable| wantAgent | Yes| **WantAgent** of the button.| -| extras | Readable and writable| Array\ | No| Extra information of the button.| -| icon | Readable and writable| image.PixelMap | No| Button icon.| -| userInput | Readable and writable| NotificationUserInput | No| User input object.| - -- NotificationUserInput - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------ | ---- | ----------------------------- | -| inputKey | Readable and writable| string | Yes| Key to identify the user input.| - - -- Return value - - void - -- Example +**Example** ```js // publish callback @@ -168,7 +35,7 @@ function publishCallback(err) { var notificationRequest = { id: 1, content: { - contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -181,24 +48,22 @@ Notification.publish(notificationRequest, publishCallback) -## Notification.publish(request: NotificationRequest) - -- Functionality +## Notification.publish - Publishes a notification. This method uses a promise to return the result. +publish(request: NotificationRequest): Promise\ -- Return value +Publishes a notification. This API uses a promise to return the result. - Promise\ +**System capability**: SystemCapability.Notification.Notification -- Example +**Example** ```js // NotificationRequest object var notificationRequest = { notificationId: 1, content: { - contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -206,33 +71,107 @@ var notificationRequest = { } } } -Notification.publish(notificationRequest).then((void) => { +Notification.publish(notificationRequest).then(() => { console.info("==========================>publishCallback=======================>"); }); ``` +## Notification.publish8+ + +publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void + +Publishes a notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| userId | Yes | No |number | Yes | ID of the user who receives the notification. | +| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +// publish callback +function publishCallback(err) { + console.info("==========================>publishCallback=======================>"); +} +// ID of the user who receives the notification. +var userId = 1 +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest, userId, publishCallback); +``` + +## Notification.publish8+ + +publish(request: NotificationRequest, userId: number): Promise\ + +Publishes a notification. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| userId | Yes | No |number | Yes | ID of the user who receives the notification. | + +**Example** + +```js +var notificationRequest = { + notificationId: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +var userId = 1 +Notification.publish(notificationRequest, userId).then(() => { + console.info("==========================>publishCallback=======================>"); +}); +``` -## Notification.cancel(id: number, label: string, callback: AsyncCallback\) -- Functionality +## Notification.cancel - Cancels a notification with the specified ID and label. This method uses a callback to return the result. +cancel(id: number, label: string, callback: AsyncCallback\): void -- Parameters +Cancels a notification with the specified ID and label. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| id | Read-only| number | Yes| Notification ID.| -| label | Read-only| string | Yes| Notification label.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | --- | ---- | --------------------- | ---- | -------------------- | +| id | Yes | No | number | Yes | Notification ID. | +| label | Yes | No | string | Yes | Notification label. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js // cancel callback @@ -244,51 +183,47 @@ Notification.cancel(0, "label", cancelCallback) -## Notification.cancel(id: number, label? : string) - -- Functionality +## Notification.cancel - Cancels a notification with the specified ID and label. This method uses a promise to return the result. +cancel(id: number, label?: string): Promise\ -- Parameters +Cancels a notification with the specified ID and label. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------ | ---- | -------- | -| id | Read-only| number | Yes| Notification ID.| -| label | Read-only| string | No| Notification label.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | --- | ---- | ------ | ---- | -------- | +| id | Yes | No | number | Yes | Notification ID. | +| label | Yes | No | string | No | Notification label.| -- Example +**Example** ```js -Notification.cancel(0).then((void) => { +Notification.cancel(0).then(() => { console.info("==========================>cancelCallback=======================>"); }); ``` -## Notification.cancel(id: number, callback: AsyncCallback\) +## Notification.cancel -- Functionality +cancel(id: number, callback: AsyncCallback\): void - Cancels a notification with the specified ID. This method uses a callback to return the result. +Cancels a notification with the specified ID. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| id | Read-only| number | Yes| Notification ID.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| id | Yes | No | number | Yes | Notification ID. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js // cancel callback @@ -300,92 +235,66 @@ Notification.cancel(0, cancelCallback) -## Notification.cancelAll(callback: AsyncCallback\) - -- Functionality +## Notification.cancelAll - Cancels all notifications. This method uses a callback to return the result. +cancelAll(callback: AsyncCallback\): void -- Parameters +Cancels all notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js // cancel callback -function cancelAllback(err) { - console.info("==========================>cancelAllback=======================>"); +function cancelAllCallback(err) { + console.info("==========================>cancelAllCallback=======================>"); } -Notification.cancelAll(cancelCallback) +Notification.cancelAll(cancelAllCallback) ``` -## Notification.cancelAll() - -- Functionality - - Cancels all notifications. This method uses a promise to return the result. +## Notification.cancelAll -- Parameters +cancelAll(): Promise\ - None +Cancels all notifications. This API uses a promise to return the result. -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ - -- Example +**Example** ```js -Notification.cancelAll().then((void) => { - console.info("==========================>cancelAllback=======================>"); +Notification.cancelAll().then(() => { + console.info("==========================>cancelAllCallback=======================>"); }); ``` -## Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\) - -- Functionality - - Adds a notification slot. This method uses a callback to return the result. - -- Parameters +## Notification.addSlot -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +addSlot(slot: NotificationSlot, callback: AsyncCallback\): void -- NotificationSlot +Adds a notification slot. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------------- | -------- | --------------- | ---- | ------------------------------------------ | -| type | Readable and writable| SlotType | Yes| Notification slot type.| -| level | Readable and writable| number | No| Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Readable and writable| string | No| Description of the notification slot.| -| badgeFlag | Readable and writable| boolean | No| Whether to display the badge.| -| bypassDnd | Readable and writable| boolean | No| Whether to bypass the system do-not-disturb (DND) setting.| -| lockscreenVisibility | Readable and writable| boolean | No| How the notification is displayed on the locked screen.| -| vibrationEnabled | Readable and writable| boolean | No| Whether vibration is enabled for the notification.| -| sound | Readable and writable| string | No| Notification sound.| -| lightEnabled | Readable and writable| boolean | No| Whether light is enabled for the notification.| -| lightColor | Readable and writable| number | No| Notification light color.| -| vibrationValues | Readable and writable| Array\ | No| Notification vibration mode.| +**System capability**: SystemCapability.Notification.Notification -* Return values +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -* Example +**Example** ```js // addSlot callback @@ -401,54 +310,50 @@ Notification.addSlot(notificationSlot, addSlotCallBack) -## Notification.addSlot(slot: NotificationSlot) +## Notification.addSlot -- Functionality +addSlot(slot: NotificationSlot): Promise\ - Adds a notification slot. This method uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ---------------- | ---- | -------------------- | -| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | ---------------- | ---- | -------------------- | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| - Promise\ - -- Example +**Example** ```js // NotificationSlot object var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -Notification.addSlot(notificationSlot).then((void) => { +Notification.addSlot(notificationSlot).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.addSlot(type: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.addSlot - Adds a notification slot. This method uses a callback to return the result. +addSlot(type: SlotType, callback: AsyncCallback\): void -- Parameters +Adds a notification slot. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------- | -| type | Read-only| SlotType | Yes| Type of the notification slot to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // addSlot callback @@ -460,50 +365,46 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack -## Notification.addSlot(type: SlotType) +## Notification.addSlot -- Functionality +addSlot(type: SlotType): Promise\ - Adds a notification slot. This method uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | -------- | ---- | ---------------------- | -| type | Read-only| SlotType | Yes| Type of the notification slot to add.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | -------- | ---- | ---------------------- | +| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| - Promise\ - -- Example +**Example** ```js -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then((void) => { +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.addSlots(slots: Array\, callback: AsyncCallback\) - -- Functionality +## Notification.addSlots - Adds multiple notification slots. This method uses a callback to return the result. +addSlots(slots: Array\, callback: AsyncCallback\): void -- Parameters +Adds multiple notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------- | ---- | ------------------------ | -| slots | Read-only| Array\ | Yes| Notification slots to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------- | ---- | ------------------------ | +| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // addSlots callback @@ -515,31 +416,29 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } // NotificationSlotArray object -var notificationSlotArray = new Array(); -notificationSlotArray[0] = notificationSlot; +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray, addSlotsCallBack) ``` -## Notification.addSlots(slots: Array\) +## Notification.addSlots -- Functionality +addSlots(slots: Array\): Promise\ - Adds multiple notification slots. This method uses a promise to return the result. +Adds multiple notification slots. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------------------------- | ---- | ------------------------ | -| slots | Read-only| Array\ | Yes| Notification slots to add.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | ---- | --- | ------------------------- | ---- | ------------------------ | +| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| - Promise\ - -- Example +**Example** ```js // NotificationSlot object @@ -547,34 +446,32 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } // NotificationSlotArray object -var notificationSlotArray = new Array(); -notificationSlotArray[0] = notificationSlot; +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray).then((void) => { +Notification.addSlots(notificationSlotArray).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.getSlot(slotType: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.getSlot - Obtains a notification slot of the specified type. This method uses a callback to return the result. +getSlot(slotType: SlotType, callback: AsyncCallback\): void -- Parameters +Obtains a notification slot of the specified type. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | -- Example +**Example** ```js // getSlot callback @@ -587,23 +484,27 @@ Notification.getSlot(slotType, getSlotCallback) -## Notification.getSlot(slotType) +## Notification.getSlot -- Functionality +getSlot(slotType: SlotType): Promise\ - Obtains a notification slot of the specified type. This method uses a promise to return the result. +Obtains a notification slot of the specified type. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | -| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| - Promise\ +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; @@ -614,23 +515,21 @@ Notification.getSlot(slotType).then((data) => { -## Notification.getSlots(callback: AsyncCallback>) - -- Functionality +## Notification.getSlots - Obtains all notification slots. This method uses a callback to return the result. +getSlots(callback: AsyncCallback>): void -- Parameters +Obtains all notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result.| -- Example +**Example** ```js // getSlots callback @@ -642,21 +541,21 @@ Notification.getSlots(getSlotsCallback) -## Notification.getSlots() +## Notification.getSlots -- Functionality +getSlots(): Promise\> - Obtains all notification slots of the current application. This method uses a promise to return the result. +Obtains all notification slots of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getSlots().then((data) => { @@ -666,24 +565,22 @@ Notification.getSlots().then((data) => { -## Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.removeSlot - Removes a notification slot of the specified type. This method uses a callback to return the result. +removeSlot(slotType: SlotType, callback: AsyncCallback\): void -- Parameters +Removes a notification slot of the specified type. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ----------------------------------------------------------- | -| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // removeSlot callback @@ -696,50 +593,46 @@ Notification.removeSlot(slotType,removeSlotCallback) -## Notification.removeSlot(slotType: SlotType) +## Notification.removeSlot -- Functionality +removeSlot(slotType: SlotType): Promise\ - Removes a notification slot of the specified type. This method uses a promise to return the result. +Removes a notification slot of the specified type. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | -| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| - Promise\ - -- Example +**Example** ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType).then((void) => { +Notification.removeSlot(slotType).then(() => { console.info("==========================>removeSlotCallback=======================>"); }); ``` -## Notification.removeAllSlots(callback: AsyncCallback\) - -- Functionality +## Notification.removeAllSlots - Removes all notification slots. This method uses a callback to return the result. +removeAllSlots(callback: AsyncCallback\): void -- Parameters +Removes all notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeAllCallBack(err) { @@ -750,111 +643,41 @@ Notification.removeAllSlots(removeAllCallBack) -## Notification.removeAllSlots() +## Notification.removeAllSlots -- Functionality +removeAllSlots(): Promise\ - Removes all notification slots. This method uses a promise to return the result. +Removes all notification slots. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None - -- Return value - - Promise\ - -- Example +**Example** ```js -Notification.removeAllSlots().then((void) => { +Notification.removeAllSlots().then(() => { console.info("==========================>removeAllCallBack=======================>"); }); ``` -## Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\) - -- Functionality +## Notification.subscribe - Subscribes to a notification with the subscription information specified. This method uses a callback to return the result. +subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void -- Parameters +Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------- | ---- | ---------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| info | Read-only| NotificationSubscribeInfo | Yes| Subscription information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- NotificationSubscriber +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------------------------------------------------------------ | -------- | -------- | ---- | -------------------------- | -| onConsume?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for receiving notifications.| -| onCancel?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for canceling notifications.| -| onUpdate?:(data: NotificationSortingMap) | Readable and writable| function | No| Callback for notification sorting updates.| -| onConnect?:() | Readable and writable| function | No| Callback for subscription.| -| onDisconnect?:() | Readable and writable| function | No| Callback for unsubscription.| -| onDestroy?:() | Readable and writable| function | No| Callback for service destruction.| -| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) | Readable and writable| function | No| Callback for DND time setting updates.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ------------------------- | ---- | ---------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Subscription information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- SubscribeCallbackData - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | ---------------------- | ---- | -------- | -| request | Read-only| NotificationRequest | Yes| Notification content.| -| sortingMap | Read-only| NotificationSortingMap | No| Notification sorting information.| -| reason | Read-only| number | No| Reason for deletion.| -| sound | Read-only| string | No| Sound used for notification.| -| vibrationValues | Read-only| Array\ | No| Vibration used for notification.| - -- NotificationSortingMap - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------------------------------------ | ---- | ---------------- | -| sortings | Read-only| {[key: string]: NotificationSorting} | Yes| Array of notification sorting information.| -| sortedHashCode | Read-only| Array\ | Yes| Array of unique notification IDs.| - -- NotificationSorting - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------- | ---- | ------------ | -| slot | Read-only| NotificationSlot | Yes| Notification slot.| -| hashCode | Read-only| string | Yes| Unique ID of the notification.| -| ranking | Read-only| number | Yes| Notification sequence number.| - -- DoNotDisturbType - - -| Name| Readable/Writable| Type| Description| -| ------------ | -------- | --------------------- | ---------------------------------------- | -| TYPE_NONE | Read-only| enum DoNotDisturbType | Non-DND.| -| TYPE_ONCE | Read-only| enum DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute)| -| TYPE_DAILY | Read-only| enum DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute)| -| TYPE_CLEARLY | Read-only| enum DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute)| - -- DoNotDisturbDate - -| Name| Readable/Writable| Type| Description| -| ----- | -------- | ---------------- | ------------------------ | -| type | Readable and writable| DoNotDisturbType | DND time type.| -| begin | Readable and writable| Date | DND start time.| -| end | Readable and writable| Date | DND end time.| - -- NotificationSubscribeInfo - -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | --------------- | ---- | ------------------------------- | -| bundleNames | Readable and writable| Array\ | No| Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Readable and writable| number | No| User whose notifications are to be subscribed to.| - -- Return value - - void - -- Example +**Example** ```js // subscribe callback @@ -875,24 +698,22 @@ Notification.subscribe(subscriber, info, subscribeCallback); -## Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) - -- Functionality +## Notification.subscribe - Subscribes to a notification. This method uses a callback to return the result. +subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -- Parameters +Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | ---------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | ---------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function subscribeCallback(err) { @@ -909,24 +730,22 @@ Notification.subscribe(subscriber, subscribeCallback); -## Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) +## Notification.subscribe -- Functionality +subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise\ - Subscribes to a notification with the subscription information specified. This method uses a promise to return the result. +Subscribes to a notification with the subscription information specified. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------- | ---- | ------------ | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| info | Read-only| NotificationSubscribeInfo | No| Subscription information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ------------------------- | ---- | ------------ | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Subscription information. | - Promise\ - -- Example +**Example** ```js function onConsumeCallback(err, data) { @@ -935,31 +754,29 @@ function onConsumeCallback(err, data) { var subscriber = { onConsume: onConsumeCallback }; -Notification.subscribe(subscriber).then((void) => { +Notification.subscribe(subscriber).then(() => { console.info("==========================>subscribeCallback=======================>"); }); ``` -## Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) - -- Functionality +## Notification.unsubscribe - Unsubscribes from a notification. This method uses a callback to return the result. +unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -- Parameters +Unsubscribes from a notification. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | -------------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | -------------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function unsubscribeCallback(err) { @@ -976,23 +793,21 @@ Notification.unsubscribe(subscriber, unsubscribeCallback); -## Notification.unsubscribe(subscriber: NotificationSubscriber) +## Notification.unsubscribe -- Functionality +unsubscribe(subscriber: NotificationSubscriber): Promise\ - Unsubscribes from a notification. This method uses a promise to return the result. +Unsubscribes from a notification. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | ------------ | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | ------------ | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| - Promise\ - -- Example +**Example** ```js function onConsumeCallback(err, data) { @@ -1001,133 +816,125 @@ function onConsumeCallback(err, data) { var subscriber = { onConsume: onConsumeCallback }; -Notification.unsubscribe(subscriber).then((void) => { +Notification.unsubscribe(subscriber).then(() => { console.info("==========================>unsubscribeCallback=======================>"); }); ``` -## Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) - -- Functionality +## Notification.enableNotification - Sets whether to enable notification for a specified bundle. This method uses a callback to return the result. +enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -- Parameters +Sets whether to enable notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to enable notification.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- BundleOption +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------ | ---- | ------ | -| bundle | Readable and writable| string | Yes| Bundle name.| -| uid | Readable and writable| number | No| User ID.| -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function enableNotificationCallback(err) { console.info("==========================>enableNotificationCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.enableNotification(bundle, false, enableNotificationCallback); ``` -## Notification.enableNotification(bundle: BundleOption, enable: boolean) - -- Functionality +## Notification.enableNotification - Sets whether to enable notification for a specified bundle. This method uses a promise to return the result. +enableNotification(bundle: BundleOption, enable: boolean): Promise\ -- Parameters +Sets whether to enable notification for a specified bundle. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to enable notification.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | Yes | No | boolean | Yes | Whether to enable notification. | -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } -Notification.enableNotification(bundle, false).then((void) => { +Notification.enableNotification(bundle, false).then(() => { console.info("==========================>enableNotificationCallback=======================>"); }); ``` -## Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\) +## Notification.isNotificationEnabled -- Functionality +isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void - Checks whether notification is enabled for a specified bundle. This method uses a callback to return the result. +Checks whether notification is enabled for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function isNotificationEnabledCallback(err, data) { console.info("==========================>isNotificationEnabledCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` -## Notification.isNotificationEnabled(bundle: BundleOption) +## Notification.isNotificationEnabled + +isNotificationEnabled(bundle: BundleOption): Promise\ -- Functionality +Checks whether notification is enabled for a specified bundle. This API uses a promise to return the result. - Checks whether notification is enabled for a specified bundle. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -- Return value +**Return value** - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { console.info("==========================>isNotificationEnabledCallback=======================>"); @@ -1136,23 +943,21 @@ Notification.isNotificationEnabled(bundle).then((data) => { -## Notification.isNotificationEnabled(callback: AsyncCallback\) - -- Functionality +## Notification.isNotificationEnabled - Checks whether notification is enabled for the current application. This method uses a callback to return the result. +isNotificationEnabled(callback: AsyncCallback\): void -- Parameters +Checks whether notification is enabled for this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function isNotificationEnabledCallback(err, data) { @@ -1164,21 +969,27 @@ Notification.isNotificationEnabled(isNotificationEnabledCallback); -## Notification.isNotificationEnabled() +## Notification.isNotificationEnabled -- Functionality +isNotificationEnabled(): Promise\ - Checks whether notification is enabled for the current application. This method uses a promise to return the result. +Checks whether notification is enabled for this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise\ +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js Notification.isNotificationEnabled().then((data) => { @@ -1188,120 +999,118 @@ Notification.isNotificationEnabled().then((data) => { -## Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) +## Notification.displayBadge -- Functionality +displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void - Sets whether to display the badge in notifications for a specified bundle. This method uses a callback to return the result. +Sets whether to enable the notification badge for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to display the badge.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function displayBadgeCallback(err) { console.info("==========================>displayBadgeCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.displayBadge(bundle, false, displayBadgeCallback); ``` -## Notification.displayBadge(bundle: BundleOption, enable: boolean) - -- Functionality +## Notification.displayBadge - Sets whether to display the badge in notifications for a specified bundle. This method uses a promise to return the result. +displayBadge(bundle: BundleOption, enable: boolean): Promise\ -- Parameters +Sets the notification slot for a specified bundle. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to display the badge.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | Yes | No | boolean | Yes | Whether to enable notification. | -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } -Notification.displayBadge(bundle, false).then((void) => { +Notification.displayBadge(bundle, false).then(() => { console.info("==========================>displayBadgeCallback=======================>"); }); ``` -## Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\) +## Notification.isBadgeDisplayed -- Functionality +isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void - Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a callback to return the result. +Checks whether the notification badge is enabled for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function isBadgeDisplayedCallback(err, data) { console.info("==========================>isBadgeDisplayedCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` -## Notification.isBadgeDisplayed(bundle: BundleOption) +## Notification.isBadgeDisplayed + +isBadgeDisplayed(bundle: BundleOption): Promise\ -- Functionality +Checks whether the notification badge is enabled for a specified bundle. This API uses a promise to return the result. - Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -- Return value +**Return value** - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { console.info("==========================>isBadgeDisplayedCallback=======================>"); @@ -1310,32 +1119,30 @@ Notification.isBadgeDisplayed(bundle).then((data) => { -## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\) - -- Functionality +## Notification.setSlotByBundle - Sets a notification slot for a specified bundle. This method uses a callback to return the result. +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void -- Parameters +Sets the notification slot for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| slot | Read-only| NotificationSlot | Yes| Notification slot.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function setSlotByBundleCallback(err) { console.info("==========================>setSlotByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION @@ -1345,91 +1152,91 @@ Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); -## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) +## Notification.setSlotByBundle -- Functionality +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ - Sets a notification slot for a specified bundle. This method uses a promise to return the result. +Sets the notification slot for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| slot| Read-only| NotificationSlot| Yes| Notification slot.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Whether to enable notification. | - Promise\ - -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -Notification.displayBadge(bundle, notificationSlot).then((void) => { +Notification.displayBadge(bundle, notificationSlot).then(() => { console.info("==========================>setSlotByBundleCallback=======================>"); }); ``` -## Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>) - -- Functionality +## Notification.getSlotsByBundle - Obtains the notification slots of a specified bundle. This method uses a callback to return the result. +getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void -- Parameters +Obtains the notification slots of a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------------------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------------------------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| -- Example +**Example** ```js function getSlotsByBundleCallback(err, data) { console.info("==========================>getSlotsByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); ``` -## Notification.getSlotsByBundle(bundle: BundleOption) +## Notification.getSlotsByBundle -- Functionality +getSlotsByBundle(bundle: BundleOption): Promise> - Obtains the notification slots of a specified bundle. This method uses a promise to return the result. +Obtains the notification slots of a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise> +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise> | Promise used to return the result.| + +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { console.info("==========================>getSlotsByBundleCallback=======================>"); @@ -1438,58 +1245,60 @@ Notification.getSlotsByBundle(bundle).then((data) => { -## Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\) - -- Functionality +## Notification.getSlotNumByBundle - Obtains the number of notification slots of a specified bundle. This method uses a callback to return the result. +getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void -- Parameters +Obtains the number of notification slots of a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------- | ---- | ---------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------- | ---- | ---------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function getSlotNumByBundle(err, data) { console.info("==========================>getSlotNumByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` -## Notification.getSlotNumByBundle(bundle: BundleOption) +## Notification.getSlotNumByBundle -- Functionality +getSlotNumByBundle(bundle: BundleOption): Promise\ - Obtains the number of notification slots of a specified bundle. This method uses a promise to return the result. +Obtains the number of notification slots of a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise\ +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { console.info("==========================>getSlotNumByBundleCallback=======================>"); @@ -1498,101 +1307,88 @@ Notification.getSlotNumByBundle(bundle).then((data) => { -## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\) - -- Functionality +## Notification.remove - Removes a notification for a specified bundle. This method uses a callback to return the result. +remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\): void -- Parameters +Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| notificationKey | Read-only| NotificationKey | Yes| Notification key.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- NotificationKey +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------ | ---- | -------- | -| id | Readable and writable| number | Yes| Notification ID.| -| label | Readable and writable| string | No| Notification label.| +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | ----------------------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Return value - - void - -- Example +**Example** ```js function removeCallback(err) { console.info("==========================>removeCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationKey = { - id: 0; - label: "label"; + id: 0, + label: "label", } Notification.remove(bundle, notificationKey, removeCallback); ``` -## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) +## Notification.remove -- Functionality +remove(bundle: BundleOption, notificationKey: NotificationKey): Promise\ - Removes a notification for a specified bundle. This method uses a promise to return the result. +Removes a notification for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | --------------- | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| notificationKey | Read-only| NotificationKey | Yes| Notification key.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | --------------- | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | - Promise\ - -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationKey = { - id: 0; - label: "label"; + id: 0, + label: "label", } -Notification.remove(bundle, notificationKey).then((void) => { +Notification.remove(bundle, notificationKey).then(() => { console.info("==========================>removeCallback=======================>"); }); ``` -## Notification.remove(hashCode: string, callback: AsyncCallback\) - -- Functionality +## Notification.remove - Removes a notification. This method uses a callback to return the result. +remove(hashCode: string, callback: AsyncCallback\): void -- Parameters +Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| hashCode | Read-only| string | Yes| Unique notification ID.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| hashCode | Yes | No | string | Yes | Unique notification ID. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeCallback(err) { @@ -1604,80 +1400,74 @@ Notification.remove(hashCode, removeCallback); -## Notification.remove(hashCode: string) +## Notification.remove -- Functionality +remove(hashCode: string): Promise\ - Removes a notification. This method uses a promise to return the result. +Removes a notification for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------- | ---- | ---------- | -| hashCode | Read-only| string | Yes| Unique notification ID.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------- | ---- | ---------- | +| hashCode | Yes | No | string | Yes | Unique notification ID.| - Promise\ - -- Example +**Example** ```js -Notification.remove(hashCode).then((void) => { +Notification.remove(hashCode).then(() => { console.info("==========================>removeCallback=======================>"); }); ``` -## Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\) - -- Functionality +## Notification.removeAll - Removes all notifications for a specified bundle. This method uses a callback to return the result. +removeAll(bundle: BundleOption, callback: AsyncCallback\): void -- Parameters +Removes all notifications for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeAllCallback(err) { console.info("==========================>removeAllCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.removeAll(bundle, removeAllCallback); ``` -## Notification.removeAll(callback: AsyncCallback\) +## Notification.removeAll -- Functionality +removeAll(callback: AsyncCallback\): void - Removes all notifications. This method uses a callback to return the result. +Removes all notifications. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function removeAllCallback(err) { @@ -1689,49 +1479,97 @@ Notification.removeAll(removeAllCallback); -## Notification.removeAll(bundle?: BundleOption) - -- Functionality +## Notification.removeAll - Removes all notifications for a specified bundle. This method uses a promise to return the result. +removeAll(bundle?: BundleOption): Promise\ -- Parameters +Removes all notifications for a specified user. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | No| Bundle information.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | No | Bundle information.| -- Example +**Example** ```js -Notification.removeAll().then((void) => { +Notification.removeAll().then(() => { console.info("==========================>removeAllCallback=======================>"); }); ``` +## Notification.removeAll8+ +removeAll(userId: number, callback: AsyncCallback\): void -## Notification.getAllActiveNotifications(callback: AsyncCallback>) +Removes all notifications for a specified user. This API uses an asynchronous callback to return the result. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains all active notifications. This method uses a callback to return the result. +**Parameters** -- Parameters +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| userId | Yes | No | number | Yes | ID of the user who receives the notification.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**Example** -- Return value +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} + +var userId = 1 + +Notification.removeAll(userId, removeAllCallback); +``` + +## Notification.removeAll8+ + +removeAll(userId: number): Promise\ + +Removes all notifications for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| userId | Yes | No | number | Yes | ID of the user who receives the notification.| + +**Example** + +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} + +var userId = 1 + +Notification.removeAll(userId, removeAllCallback); +``` + + +## Notification.getAllActiveNotifications - void +getAllActiveNotifications(callback: AsyncCallback>): void -- Example +Obtains all active notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------------------------------ | ---- | -------------------- | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| + +**Example** ```js function getAllActiveNotificationsCallback(err, data) { @@ -1743,21 +1581,21 @@ Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); -## Notification.getAllActiveNotifications() +## Notification.getAllActiveNotifications -- Functionality +getAllActiveNotifications(): Promise\\> - Obtains all active notifications. This method uses a promise to return the result. +Obtains all active notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getAllActiveNotifications().then((data) => { @@ -1767,23 +1605,21 @@ Notification.getAllActiveNotifications().then((data) => { -## Notification.getActiveNotificationCount(callback: AsyncCallback\) - -- Functionality +## Notification.getActiveNotificationCount - Obtains the number of active notifications. This method uses a callback to return the result. +getActiveNotificationCount(callback: AsyncCallback\): void -- Parameters +Obtains the number of active notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------------- | ---- | ---------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function getActiveNotificationCountCallback(err, data) { @@ -1795,21 +1631,21 @@ Notification.getActiveNotificationCount(getActiveNotificationCountCallback); -## Notification.getActiveNotificationCount() +## Notification.getActiveNotificationCount -- Functionality +getActiveNotificationCount(): Promise\ - Obtains the number of active notifications. This method uses a promise to return the result. +Obtains the number of active notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| - Promise\ - -- Example +**Example** ```js Notification.getActiveNotificationCount().then((data) => { @@ -1819,23 +1655,21 @@ Notification.getActiveNotificationCount().then((data) => { -## Notification.getActiveNotifications(callback: AsyncCallback>) - -- Functionality +## Notification.getActiveNotifications - Obtains active notifications of the current application. This method uses a callback to return the result. +getActiveNotifications(callback: AsyncCallback>): void -- Parameters +Obtains active notifications of this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------------------ | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| -- Example +**Example** ```js function getActiveNotificationsCallback(err, data) { @@ -1847,21 +1681,21 @@ Notification.getActiveNotifications(getActiveNotificationsCallback); -## Notification.getActiveNotifications() +## Notification.getActiveNotifications -- Functionality +getActiveNotifications(): Promise\\> - Obtains active notifications. This method uses a promise to return the result. +Obtains active notifications of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getActiveNotifications().then((data) => { @@ -1871,24 +1705,22 @@ Notification.getActiveNotifications().then((data) => { -## Notification.cancelGroup(groupName: string, callback: AsyncCallback\) - -- Functionality +## Notification.cancelGroup8+ - Cancels a notification group of the current application. This method uses a callback to return the result. +cancelGroup(groupName: string, callback: AsyncCallback\): void -- Parameters +Cancels a notification group of this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ---------------------------- | -| groupName | Read-only| string | Yes| Name of the notification group to cancel.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| groupName | Yes | No | string | Yes | Name of the notification group. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function cancelGroupCallback(err) { @@ -1902,23 +1734,21 @@ Notification.cancelGroup(groupName, cancelGroupCallback); -## Notification.cancelGroup(groupName: string) +## Notification.cancelGroup8+ -- Functionality +cancelGroup(groupName: string): Promise\ - Cancels a notification group of the current application. This method uses a promise to return the result. +Cancels a notification group of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | ------ | ---- | -------------- | -| groupName | Read-only| string | Yes| Name of the notification group to cancel.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | ------ | ---- | -------------- | +| groupName | Yes | No | string | Yes | Name of the notification group.| - Promise\ - -- Example +**Example** ```js var groupName = "GroupName"; @@ -1929,25 +1759,23 @@ Notification.cancelGroup(groupName).then(() => { -## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\) - -- Functionality +## Notification.removeGroupByBundle8+ - Removes a notification group for a specified bundle. This method uses a callback to return the result. +removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void -- Parameters +Removes a notification group for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ---------------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| groupName | Read-only| string | Yes| Name of the notification group to remove.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | Yes | No | string | Yes | Name of the notification group. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeGroupByBundleCallback(err) { @@ -1962,24 +1790,22 @@ Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCal -## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) +## Notification.removeGroupByBundle8+ -- Functionality +removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ - Removes a notification group for a specified bundle. This method uses a promise to return the result. +Removes a notification group for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | ------------ | ---- | -------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| groupName | Read-only| string | Yes| Name of the notification group to remove.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | ------------ | ---- | -------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | Yes | No | string | Yes | Name of the notification group.| - Promise\ - -- Example +**Example** ```js var bundleOption = {bundle: "Bundle"}; @@ -1991,24 +1817,22 @@ Notification.removeGroupByBundle(bundleOption, groupName).then(() => { -## Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\) - -- Functionality +## Notification.setDoNotDisturbDate8+ - Sets the DND time. This method uses a callback to return the result. +setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void -- Parameters +Sets the DND time. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------- | -| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function setDoNotDisturbDateCallback(err) { @@ -2016,7 +1840,7 @@ function setDoNotDisturbDateCallback(err) { } var doNotDisturbDate = { - type: notification.DoNotDisturbType.TYPE_ONCE, + type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) } @@ -2026,27 +1850,25 @@ Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); -## Notification.setDoNotDisturbDate(date: DoNotDisturbDate) +## Notification.setDoNotDisturbDate8+ -- Functionality +setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ - Sets the DND time. This method uses a promise to return the result. +Sets the DND time. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ---------------- | ---- | -------------- | -| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | ---------------- | ---- | -------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| - Promise\ - -- Example +**Example** ```js var doNotDisturbDate = { - type: notification.DoNotDisturbType.TYPE_ONCE, + type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) } @@ -2056,24 +1878,89 @@ Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { ``` +## Notification.setDoNotDisturbDate8+ + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback\): void + +Sets the DND time for a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| userId | Yes | No | number | Yes | User ID.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +function setDoNotDisturbDateCallback(err) { + console.info("==========================>setDoNotDisturbDateCallback=======================>"); +} + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); +``` + + + +## Notification.setDoNotDisturbDate8+ + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ + +Sets the DND time for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification -## Notification.getDoNotDisturbDate(callback: AsyncCallback\) +**Parameters** -- Functionality +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ---------------- | ---- | -------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| userId | Yes | No | number | Yes | User ID.| - Obtains the DND time. This method uses a callback to return the result. +**Example** -- Parameters +```js +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { + console.info("==========================>setDoNotDisturbDatePromise=======================>"); +}); +``` + + +## Notification.getDoNotDisturbDate8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | ---------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +getDoNotDisturbDate(callback: AsyncCallback\): void -- Return value +Obtains the DND time. This API uses an asynchronous callback to return the result. - void +**System capability**: SystemCapability.Notification.Notification -- Example +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| + +**Example** ```js function getDoNotDisturbDateCallback(err,data) { @@ -2085,21 +1972,21 @@ Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); -## Notification.getDoNotDisturbDate() +## Notification.getDoNotDisturbDate8+ -- Functionality +getDoNotDisturbDate(): Promise\ - Obtains the DND time. This method uses a promise to return the result. +Obtains the DND time. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| - Promise\ - -- Example +**Example** ```js Notification.getDoNotDisturbDate().then((data) => { @@ -2108,24 +1995,81 @@ Notification.getDoNotDisturbDate().then((data) => { ``` +## Notification.getDoNotDisturbDate8+ + +getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void + +Obtains the DND time of a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| userId | Yes | No | number | Yes | User ID.| + +**Example** + +```js +function getDoNotDisturbDateCallback(err,data) { + console.info("==========================>getDoNotDisturbDateCallback=======================>"); +} + +var userId = 1 + +Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); +``` + + + +## Notification.getDoNotDisturbDate8+ -## Notification.supportDoNotDisturbMode(callback: AsyncCallback\) +getDoNotDisturbDate(userId: number): Promise\ -- Functionality +Obtains the DND time of a specified user. This API uses a promise to return the result. - Checks whether the DND mode is supported. This method uses a callback to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------ | ---- | -------------------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| userId | Yes | No | number | Yes | User ID.| -- Return value +**Return value** - void +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| -- Example +**Example** + +```js +var userId = 1 + +Notification.getDoNotDisturbDate(userId).then((data) => { + console.info("==========================>getDoNotDisturbDatePromise=======================>"); +}); +``` + + +## Notification.supportDoNotDisturbMode8+ + +supportDoNotDisturbMode(callback: AsyncCallback\): void + +Checks whether the DND mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------ | ---- | -------------------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** ```js function supportDoNotDisturbModeCallback(err,data) { @@ -2137,21 +2081,21 @@ Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); -## Notification.supportDoNotDisturbMode() +## Notification.supportDoNotDisturbMode8+ -- Functionality +supportDoNotDisturbMode(): Promise\ - Checks whether the DND mode is supported. This method uses a promise to return the result. +Checks whether the DND mode is supported. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value - - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js Notification.supportDoNotDisturbMode().then((data) => { @@ -2161,20 +2105,22 @@ Notification.supportDoNotDisturbMode().then((data) => { -## Notification.isSupportTemplate +## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string, callback: AsyncCallback\): void -Checks whether a specified template exists. This method uses a callback to return the result. +Checks whether a specified template exists. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Type| Mandatory| Description| +**Parameters** + +| Name | Type | Mandatory| Description | | ------------ | ------------------------ | ---- | -------------------------- | -| templateName | string | Yes| Template name.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| templateName | string | Yes | Template name. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```javascript var templateName = 'process'; @@ -2187,25 +2133,27 @@ Notification.isSupportTemplate(templateName, isSupportTemplateCallback); -## Notification.isSupportTemplate +## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string): Promise\ -Checks whether a specified template exists. This method uses a promise to return the result. +Checks whether a specified template exists. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Type| Mandatory| Description| +**Parameters** + +| Name | Type | Mandatory| Description | | ------------ | ------ | ---- | -------- | -| templateName | string | Yes| Name| +| templateName | string | Yes | Template name.| -- Return value +**Return value** -| Type| Description| +| Type | Description | | ------------------ | --------------- | | Promise\ | Promise used to return the result.| -- Example +**Example** ```javascript var templateName = 'process'; @@ -2217,974 +2165,961 @@ Notification.isSupportTemplate(templateName).then((data) => { -## NotificationTemplate +## Notification.requestEnableNotification8+ -Describes the template information. +requestEnableNotification(callback: AsyncCallback\): void -| Name| Type| Readable| Writable| Description| -| ---- | ---------------------- | ---- | ---- | -------- | -| name | string | Yes| Yes| Template name.| -| data | {[key:string]: Object} | Yes| Yes| Template data.| +Requests notification to be enabled for this application. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Notification.Notification +**Parameters** -## WantAgent APIs +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -## Modules to Import +**Example** -```js -import WantAgent from '@ohos.wantAgent'; +```javascript +function requestEnabledNotificationCallback() { + console.log('------------- requestEnabledNotification --------------'); +}; + +Notification.requestEnabledNotification(requestEnabledNotificationCallback); ``` -## WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\) -- Functionality - Obtains a **WantAgent** object. This method uses a callback to return the result. +## Notification.requestEnableNotification8+ -- Parameters +requestEnableNotification(): Promise\ +Requests notification to be enabled for this application. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------------------------- | ---- | ----------------------- | -| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- WantAgentInfo +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------------------------------- | ---- | ---------------------- | -| wants | Readable and writable| Array\ | Yes| Array of all **Want** objects.| -| operationType | Readable and writable| wantAgent.OperationType | Yes| Type of the operation specified in a **Want** object.| -| requestCode | Readable and writable| number | Yes| Request code defined by the user.| -| wantAgentFlags | Readable and writable| Array | No| Array of flags for using the **WantAgent** object.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| +```javascript +Notification.requestEnableNotification() + .then(() => { + console.info("requestEnableNotification "); + }); +``` -- - WantAgentFlags +## Notification.enableDistributed8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| ------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| ONE_TIME_FLAG | Read-only| enum | No| The **WantAgent** object can be used only once.| -| NO_BUILD_FLAG | Read-only| enum | No| The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned.| -| CANCEL_PRESENT_FLAG | Read-only| enum | No| The existing **WantAgent** object should be canceled before a new object is generated.| -| UPDATE_PRESENT_FLAG | Read-only| enum | No| Extra data of the existing **WantAgent** object is replaced with that of the new object.| -| CONSTANT_FLAG | Read-only| enum | No| The **WantAgent** object is immutable.| +enableDistributed(enable: boolean, callback: AsyncCallback\): void -- OperationType +Sets whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------------- | -------- | ---- | ---- | ----------------------- | -| UNKNOWN_TYPE | Read-only| enum | No| Unknown operation.| -| START_ABILITY | Read-only| enum | No| Starts an ability with a UI.| -| START_ABILITIES | Read-only| enum | No| Starts multiple abilities with a UI.| -| START_SERVICE | Read-only| enum | No| Starts an ability without a UI.| -| SEND_COMMON_EVENT | Read-only| enum | No| Sends a common event.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +```javascript +function enabledNotificationCallback() { + console.log('----------- enableDistributed ------------'); +}; -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +var enable = true -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +Notification.enableDistributed(enable, enabledNotificationCallback); ``` -## WantAgent.getWantAgent(info: WantAgentInfo): Promise\ +## Notification.enableDistributed8+ -- Functionality +enableDistributed(enable: boolean): Promise\ - Obtains a **WantAgent** object. This method uses a promise to return the result. +Sets whether this device supports distributed notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ------------- | ---- | ------------- | -| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| -- Return value +**Example** - Promise\ +```javascript +var enable = true -- Example +Notification.enableDistributed(enable) + .then(() => { + console.log('-------- enableDistributed ----------'); + }); +``` -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +## Notification.isDistributedEnabled8+ -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); -}); -``` +isDistributedEnabled(callback: AsyncCallback\): void +Obtains whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Notification.Notification -## WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\) +**Parameters** -- Functionality +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| - Obtains the bundle name of a **WantAgent** object. This method uses a callback to return the result. +**Example** -- Parameters +```javascript +function isDistributedEnabledCallback() { + console.log('----------- isDistributedEnabled ------------'); +}; +Notification.enableDistributed(isDistributedEnabledCallback); +``` -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ----------------------- | ---- | --------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| -- Return value - void +## Notification.isDistributedEnabled8+ -- Example +isDistributedEnabled(): Promise\ -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Obtains whether this device supports distributed notifications. This API uses a promise to return the result. -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +**Return value** -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +| Type | Description | +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| -// getBundleName callback -function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); -} -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +**Example** + +```javascript +Notification.isDistributedEnabled() + .then((data) => { + console.log('-------- isDistributedEnabled ----------'); + }); ``` +## Notification.enableDistributedByBundle8+ -## WantAgent.getBundleName(agent: WantAgent): Promise\ +enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -- Functionality +Sets whether an application supports distributed notifications based on the bundle. This API uses an asynchronous callback to return the result. - Obtains the bundle name of a **WantAgent** object. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| +**Example** -- Return value +```javascript +function enableDistributedByBundleCallback() { + console.log('----------- enableDistributedByBundle ------------'); +}; - Promise\ +var bundle = { + bundle: "bundleName1", +} -- Example +var enable = true -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundleCallback); +``` -// WantAgent object -var wantAgent; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] + +## Notification.enableDistributedByBundle8+ + +bundleenableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise + +Sets whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", } -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var enable = true -WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); -}); +Notification.enableDistributedByBundle(bundle, enable) + .then(() => { + console.log('-------- enableDistributedByBundle ----------'); + }); ``` +## Notification.isDistributedEnabledByBundle8+ +isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\): void -## WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\) +Obtains whether an application supports distributed notifications based on the bundle. This API uses an asynchronous callback to return the result. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains the user ID of a **WantAgent** object. This method uses a callback to return the result. +**Parameters** -- Parameters +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ----------------------- | ---- | ----------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +```javascript +function isDistributedEnabledByBundleCallback(data) { + console.log('----------- isDistributedEnabledByBundle ------------', data); +}; -- Return value +var bundle = { + bundle: "bundleName1", +} - void +Notification.enableDistributedByBundle(bundle, isDistributedEnabledByBundleCallback); +``` -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgent object -var wantAgent; +## Notification.isDistributedEnabledByBundle8+ -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +isDistributedEnabledByBundle(bundle: BundleOption): Promise\ -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +Obtains whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. -// getUid callback -function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", } -WantAgent.getUid(wantAgent, getUidCallback) + +Notification.isDistributedEnabledByBundle(bundle) + .then((data) => { + console.log('-------- isDistributedEnabledByBundle ----------', data); + }); ``` +## Notification.getDeviceRemindType8+ -## WantAgent.getUid(agent: WantAgent): Promise\ +getDeviceRemindType(callback: AsyncCallback\): void -- Functionality +Obtains the notification reminder type. This API uses an asynchronous callback to return the result. - Obtains the user ID of a **WantAgent** object. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8)\> | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| +**Example** -- Return value +```javascript +function getDeviceRemindTypeCallback(data) { + console.log('----------- getDeviceRemindType ------------', data); +}; - Promise\ +Notification.getDeviceRemindType(getDeviceRemindTypeCallback); +``` -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgent object -var wantAgent; +## Notification.getDeviceRemindType8+ -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +getDeviceRemindType(): Promise\ -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +Obtains the notification reminder type. This API uses a promise to return the result. -WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); -}); +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\<[DeviceRemindType](#deviceremindtype8)\> | Promise used to return the result.| + +**Example** + +```javascript +Notification.getDeviceRemindType() + .then((data) => { + console.log('-------- getDeviceRemindType ----------', data); + }); ``` +## NotificationSubscriber + +### onConsume + +onConsume?:(data: [SubscribeCallbackData](#subscribecallbackdata)) +Callback for receiving notifications. -## WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\) +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -- Functionality +function onConsumeCallback(data) { + console.info('===> onConsume in test'); + let req = data.request; + console.info('===> onConsume callback req.id:' + req.id); + let wantAgent = data.wantAgent; + wantAgent .getWant(wantAgent) + .then((data1) => { + console.log('===> getWant success want:' + JSON.stringfy(data1)); + }) + .catch((err) => { + console.error('===> getWant failed because' + JSON.stringfy(err)); + }); + console.info('===> onConsume callback req.wantAgent:' + JSON.stringfy(req.wantAgent)); +}; - Obtains the want in a **WantAgent** object. This method uses a callback to return the result. +var subscriber = { + onConsume: onConsumeCallback +}; -- Parameters +Notification.subscribe(subscriber, subscribeCallback); +``` +### onCancel -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) -- Return value +Callback for removing notifications. - void +**System capability**: SystemCapability.Notification.Notification -- Example +**Parameters** -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| -// WantAgent object -var wantAgent; +**Example** -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); } else { - console.info('----getWantAgent failed!----'); + console.info("subscribeCallback"); } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentWantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +function onCancelCallback(data) { + console.info('===> onCancel in test'); + let req = data.request; + console.info('===> onCancel callback req.id:' + req.id); } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +var subscriber = { + onCancel: onCancelCallback +}; -// getWant callback -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) +Notification.subscribe(subscriber, subscribeCallback); ``` +### onUpdate +onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) -## WantAgent.getWant(agent: WantAgent): Promise\ +Callback for notification sorting updates. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains the want in a **WantAgent** object. This method uses a promise to return the result. +**Parameters** -- Parameters +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Notification information returned.| +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object.| +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -- Return value +function onUpdateCallback() { + console.info('===> onUpdate in test'); +} - Promise\ +var subscriber = { + onUpdate: onUpdateCallback +}; -- Example +Notification.subscribe(subscriber, subscribeCallback); +``` -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +### onConnect -// WantAgent object -var wantAgent; +onConnect?:void -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +Callback for subscription. + +**System capability**: SystemCapability.Notification.Notification + +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); } -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var subscriber = { + onConnect: onConnectCallback +}; -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); -}); +Notification.subscribe(subscriber, subscribeCallback); ``` +### onDisconnect +onDisconnect?:void -## WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\) +Callback for unsubscription. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Cancels a **WantAgent** object. This method uses a callback to return the result. +**Example** -- Parameters +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; +function onDisconnectCallback() { + console.info('===> onDisconnect in test'); +} -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | --------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +var subscriber = { + onDisconnect: onDisconnectCallback +}; -- Return value +Notification.subscribe(subscriber, subscribeCallback); +``` - void +### onDestroy -- Example +onDestroy?:void -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Callback for service disconnection. -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); } else { - console.info('----getWantAgent failed!----'); + console.info("subscribeCallback"); } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +function onDestroyCallback() { + console.info('===> onDestroy in test'); } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +var subscriber = { + onDestroy: onDestroyCallback +}; -// cancel callback -function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); -} -WantAgent.cancel(wantAgent, cancelCallback) +Notification.subscribe(subscriber, subscribeCallback); ``` +### onDoNotDisturbDateChange8+ + +onDoNotDisturbDateChange?:(mode: Notification.[DoNotDisturbDate](#donotdisturbdate8)) + +Callback for DND time setting updates. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| mode | Notification.[DoNotDisturbDate](#donotdisturbdate8) | Yes| DND time setting updates.| + +**Example** +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; +function onDoNotDisturbDateChangeCallback() { + console.info('===> onDoNotDisturbDateChange in test'); +} -## WantAgent.cancel(agent: WantAgent): Promise\ +var subscriber = { + onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback +}; -- Functionality +Notification.subscribe(subscriber, subscribeCallback); +``` - Cancels a **WantAgent** object. This method uses a promise to return the result. -- Parameters +### onEnabledNotificationChanged8+ +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| +Listens for the notification enable status changes. This API uses an asynchronous callback to return the result. -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ +**Parameters** -- Example +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata8)\> | Yes| Callback used to return the result.| -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +**Example** -// WantAgent object -var wantAgent; +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +function onEnabledNotificationChangedCallback(err, callbackData) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("bundle: ", callbackData.bundle); + console.info("uid: ", callbackData.uid); + console.info("enable: ", callbackData.enable); + } +}; -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var subscriber = { + onEnabledNotificationChanged: onEnabledNotificationChangedCallback +}; -WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); -}); +Notification.subscribe(subscriber, subscribeCallback); ``` +## SubscribeCallbackData +**System capability**: SystemCapability.Notification.Notification -## WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | ------------------------------------------------- | ---- | -------- | +| request | Yes | No | [NotificationRequest](#notificationrequest) | Yes | Notification content.| +| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | No | Notification sorting information.| +| reason | Yes | No | number | No | Reason for deletion.| +| sound | Yes | No | string | No | Sound used for notification.| +| vibrationValues | Yes | No | Array\ | No | Vibration used for notification.| -- Functionality - Triggers a **WantAgent** object. This method uses a callback to return the result. +## EnabledNotificationCallbackData8+ -- Parameters +**System capability**: SystemCapability.Notification.Notification +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------- | ---- | ---------------- | +| bundle | Yes | No | string | Yes | Bundle name of the application. | +| uid | Yes | No | number | Yes | UID of the application. | +| enable | Yes | No | boolean | Yes | Notification enable status of the application.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | ----------------------------- | ---- | ------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to trigger.| -| triggerInfo | Read-only| TriggerInfo | Yes| **TriggerInfo** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| -- TriggerInfo +## DoNotDisturbDate8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | -------------------- | ---- | ----------- | -| code | Readable and writable| number | Yes| Result code.| -| want | Readable and writable| Want | No| Want.| -| permission | Readable and writable| string | No| Permission.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| +**System capability**: SystemCapability.Notification.Notification -- Return value +| Name | Readable| Writable| Type | Description | +| ----- | ---- | --- | ------------------------------------- | ------------------------ | +| type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| +| begin | Yes | No | Date | DND start time.| +| end | Yes | No | Date | DND end time.| - void -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## DoNotDisturbType8+ -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +| Name | Value | Description | +| ------------ | ---------------- | ------------------------------------------ | +| TYPE_NONE | DoNotDisturbType | Non-DND. | +| TYPE_ONCE | DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute).| +| TYPE_DAILY | DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute).| +| TYPE_CLEARLY | DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute). | -//Trigger callback -function triggerCallback(err, data) { - console.info("==========================>triggerCallback=======================>"); -} -var triggerInfo = { - code:0 -} -WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) -``` +## ContentType +**System capability**: SystemCapability.Notification.Notification +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| NOTIFICATION_CONTENT_BASIC_TEXT | ContentType | Normal text notification. | +| NOTIFICATION_CONTENT_LONG_TEXT | ContentType | Long text notification. | +| NOTIFICATION_CONTENT_PICTURE | ContentType | Picture-attached notification. | +| NOTIFICATION_CONTENT_CONVERSATION | ContentType | Conversation notification. | +| NOTIFICATION_CONTENT_MULTILINE | ContentType | Multi-line text notification.| -## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\) +## SlotLevel -- Functionality +**System capability**: SystemCapability.Notification.Notification - Checks whether two **WantAgent** objects are equal. This method uses a callback to return the result. +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| LEVEL_NONE | 0 | The notification feature is disabled. | +| LEVEL_MIN | 1 | The notification feature is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| +| LEVEL_LOW | 2 | The notification feature is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| +| LEVEL_DEFAULT | 3 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| +| LEVEL_HIGH | 4 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| -- Parameters +## BundleOption -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------ | ---- | --------------------------------------- | -| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| -| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------ | ---- | ------ | +| bundle | Yes | Yes | string | Yes | Bundle name. | +| uid | Yes | Yes | number | No | User ID.| - void -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## NotificationKey -// WantAgent object -var wantAgent1; -var wantAgent2; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent1 = data; - wantAgent2 = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | ---- | --- | ------ | ---- | -------- | +| id | Yes | Yes | number | Yes | Notification ID. | +| label | Yes | Yes | string | No | Notification label.| -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) -// equal callback -function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); -} -WantAgent.equal(wantAgent1, wantAgent2, equalCallback) -``` +## SlotType +**System capability**: SystemCapability.Notification.Notification +| Name | Value | Description | +| -------------------- | -------- | ---------- | +| UNKNOWN_TYPE | SlotType | Unknown type.| +| SOCIAL_COMMUNICATION | SlotType | Notification slot for social communication.| +| SERVICE_INFORMATION | SlotType | Notification slot for service information.| +| CONTENT_INFORMATION | SlotType | Notification slot for content consultation.| +| OTHER_TYPES | SlotType | Notification slot for other purposes.| -## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -- Functionality +## NotificationActionButton - Checks whether two **WantAgent** objects are equal. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | --- | ---- | ----------------------------------------------- | ---- | ------------------------- | +| title | Yes | Yes | string | Yes | Button title. | +| wantAgent | Yes | Yes | WantAgent | Yes | **WantAgent** of the button.| +| extras | Yes | Yes | { [key: string]: any } | No | Extra information of the button. | -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| -| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| +## NotificationBasicContent -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | ---- | ------ | ---- | ---------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## NotificationLongTextContent -// WantAgent object -var wantAgent1; -var wantAgent2; +**System capability**: SystemCapability.Notification.Notification -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | ------ | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| longText | Yes | Yes | string | Yes | Long text of the notification. | +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent1 = data; - wantAgent2 = data; -}); -WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); -}); -``` +## NotificationMultiLineContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | --- | --- | --------------- | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| longTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | +| lines | Yes | Yes | Array\ | Yes | Multi-line text of the notification. | + + +## NotificationPictureContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | -------------- | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | +| picture | Yes | Yes | image.PixelMap | Yes | Picture attached to the notification. | + + +## NotificationContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ----------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------ | +| contentType | Yes | Yes | [ContentType](#contenttype) | Yes | Notification content type. | +| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | No | Normal text. | +| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | No | Long text.| +| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | No | Multi-line text. | +| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | No | Picture-attached. | + + +## NotificationFlagStatus8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Value | Description | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | The default flag is used. | +| TYPE_OPEN | 1 | The notification flag is enabled. | +| TYPE_CLOSE | 2 | The notification flag is disabled. | + + +## NotificationFlags8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------------- | ---- | ---- | ---------------------- | ---- | --------------------------------- | +| soundEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable vibration for the notification. | + + +## NotificationRequest + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------------- | ---- | --- | --------------------------------------------- | ---- | -------------------------- | +| content | Yes | Yes | [NotificationContent](#notificationcontent) | Yes | Notification content. | +| id | Yes | Yes | number | No | Notification ID. | +| slotType | Yes | Yes | [SlotType](#slottype) | No | Slot type. | +| isOngoing | Yes | Yes | boolean | No | Whether the notification is an ongoing notification. | +| isUnremovable | Yes | Yes | boolean | No | Whether the notification can be removed. | +| deliveryTime | Yes | Yes | number | No | Time when the notification is sent. | +| tapDismissed | Yes | Yes | boolean | No | Whether the notification is automatically cleared. | +| autoDeletedTime | Yes | Yes | number | No | Time when the notification is automatically cleared. | +| wantAgent | Yes | Yes | WantAgent | No | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | Yes | Yes | {[key: string]: any} | No | Extended parameters. | +| color | Yes | Yes | number | No | Background color of the notification. | +| colorEnabled | Yes | Yes | boolean | No | Whether the notification background color is enabled. | +| isAlertOnce | Yes | Yes | boolean | No | Whether the notification triggers an alert only once.| +| isStopwatch | Yes | Yes | boolean | No | Whether to display the stopwatch. | +| isCountDown | Yes | Yes | boolean | No | Whether to display the countdown time. | +| isFloatingIcon | Yes | Yes | boolean | No | Whether the notification is displayed as a floating icon. | +| label | Yes | Yes | string | No | Notification label. | +| badgeIconStyle | Yes | Yes | number | No | Notification badge type. | +| showDeliveryTime | Yes | Yes | boolean | No | Whether to display the time when the notification is delivered. | +| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | No | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | Yes | Yes | PixelMap | No | Small notification icon. | +| largeIcon | Yes | Yes | PixelMap | No | Large notification icon. | +| creatorBundleName | Yes | No | string | No | Name of the bundle that creates the notification. | +| creatorUid | Yes | No | number | No | UID used for creating the notification. | +| creatorPid | Yes | No | number | No | PID used for creating the notification. | +| creatorUserId8+| Yes | No | number | No | ID of the user who creates a notification. | +| hashCode | Yes | No | string | No | Unique ID of the notification. | +| classification | Yes | Yes | string | No | Notification category. | +| groupName8+| Yes | Yes | string | No | Group notification name. | +| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | No | Notification template. | +| isRemoveAllowed8+ | Yes | No | boolean | No | Whether the notification can be removed. | +| source8+ | Yes | No | number | No | Notification source. | +| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | No | Option of distributed notification. | +| deviceId8+ | Yes | No | string | No | Device ID of the notification source. | +| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | No | Notification flags. | + + +## DistributedOptions8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------------------- | ---- | ---- | -------------- | ---- | ---------------------------------- | +| isDistributed | Yes | Yes | boolean | No | Whether the notification is a distributed notification. | +| supportDisplayDevices | Yes | Yes | Array\ | Yes | Types of the devices to which the notification can be synchronized. | +| supportOperateDevices | Yes | Yes | Array\ | No | Devices on which notification can be enabled. | +| remindType | Yes | No | number | No | Notification reminder type. | + + +## NotificationSlot + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------------- | ---- | --- | --------------------- | ---- | ------------------------------------------ | +| type | Yes | Yes | [SlotType](#slottype) | Yes | Slot type. | +| level | Yes | Yes | number | No | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | Yes | Yes | string | No | Notification slot description. | +| badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. | +| bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. | +| lockscreenVisibility | Yes | Yes | boolean | No | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | +| sound | Yes | Yes | string | No | Notification alert tone. | +| lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | +| lightColor | Yes | Yes | number | No | Indicator color of the notification. | +| vibrationValues | Yes | Yes | Array\ | No | Vibration mode of the notification. | + + +## NotificationSorting + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------- | ---- | ------------ | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot content.| +| hashCode | Yes | No | string | Yes | Unique ID of the notification.| +| ranking | Yes | No | number | Yes | Notification sequence number.| + + +## NotificationSortingMap + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | ------------------------------------------------------------ | ---- | ---------------- | +| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | Array of notification sorting information.| +| sortedHashCode | Yes | No | Array\ | Yes | Array of unique notification IDs.| + + +## NotificationSubscribeInfo + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ----------- | --- | ---- | --------------- | ---- | ------------------------------- | +| bundleNames | Yes | Yes | Array\ | No | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | Yes | Yes | number | No | User whose notifications are to be subscribed to. | + + +## NotificationTemplate8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name| Type | Readable| Writable| Description | +| ---- | ---------------------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Template name.| +| data | {[key:string]: Object} | Yes | Yes | Template data.| + + +## NotificationUserInput8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | --- | ---- | ------ | ---- | ----------------------------- | +| inputKey | Yes | Yes | string | Yes | Key to identify the user input.| + +## DeviceRemindType8+ +**System capability**: SystemCapability.Notification.Notification -#### +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| IDLE_DONOT_REMIND | 0 | The device is not in use. No notification is required. | +| IDLE_REMIND | 1 | The device is not in use. | +| ACTIVE_DONOT_REMIND | 2 | The device is in use. No notification is required. | +| ACTIVE_REMIND | 3 | The device is in use. | diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index cc75cd19bc..29d9e85a23 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -278,7 +278,7 @@ Registers an observer for connection status change events of the cellular data l | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** @@ -303,7 +303,7 @@ Registers an observer for connection status change events of the cellular data l | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** @@ -331,7 +331,7 @@ Unregisters the observer for connection status change events of the cellular dat | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 6de662feea..de757b71b4 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -29,6 +29,7 @@ Obtains an **AccountManager** instance. ``` ## OsAccountType + Enumerates OS account types. **System capability**: SystemCapability.Account.OsAccount @@ -51,6 +52,8 @@ Activates an OS account. This method uses an asynchronous callback to return the This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + **System capability**: SystemCapability.Account.OsAccount **Parameters** @@ -488,7 +491,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean,callback: AsyncCallback<void>): void -Sets or removes constraints for an OS account. +Sets or removes constraints for an OS account. This method uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -519,7 +522,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> -Sets or removes constraints for an OS account. +Sets or removes constraints for an OS account. This method uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1737,16 +1740,17 @@ This is a system API and cannot be called by third-party applications. ``` ## OsAccountInfo + Defines information about an OS account. **System capability**: SystemCapability.Account.OsAccount -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | --------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| localName | string | Yes | OS account name. | -| type | [OsAccountType](#osaccounttype) | Yes | OS account type. | -| constraints | Array<string> | No | [Constraints](#constraints) on the OS account.| +| Name | Type | Mandatory| Description | +| ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| localName | string | Yes | OS account name. | +| type | [OsAccountType](#osaccounttype) | Yes | OS account type. | +| constraints | Array<string> | No | [Constraints](#constraints) on the OS account.| | isVerified8+ | boolean | Yes | Whether the OS account is verified. | | photo8+ | string | No | Profile photo of the OS account. | | createTime8+ | number | Yes | Time when the OS account was created. | @@ -1754,17 +1758,18 @@ Defines information about an OS account. | serialNumber8+ | number | Yes | SN of the OS account. | | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | -| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | +| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | | domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | ## DomainAccountInfo8+ + Domain account information. **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | -| domain | string | Yes | Domain name. | +| domain | string | Yes | Domain name. | | accountName | string | Yes | Domain account name.| ## Constraints @@ -1801,8 +1806,8 @@ Domain account information. | constraint.control.apps | A user is not allowed to modify apps in **Settings** or the boot module.| | constraint.physical.media | A user is not allowed to mount external physical media.| | constraint.microphone | A user is not allowed to use microphones.| -| constraint.microphone.unmute | A user is not allowed to adjust the microphone volume.| -| constraint.volume.adjust | A user is not allowed to adjust the device's global volume.| +| constraint.microphone.unmute | A user is not allowed to unmute the microphone.| +| constraint.volume.adjust | A user is not allowed to adjust the volume.| | constraint.calls.outgoing | A user is not allowed to make outgoing calls.| | constraint.sms.use | A user is not allowed to send or receive SMS messages.| | constraint.fun | A user is not allowed to have entertainment.| @@ -1820,7 +1825,7 @@ Domain account information. | constraint.os.account.set.icon | A user is not allowed to change their icon.| | constraint.wallpaper.set | A user is not allowed to set a wallpaper.| | constraint.oem.unlock | A user is not allowed to enable OEM unlock.| -| constraint.device.unmute | A user is not allowed to mute the device's global volume.| +| constraint.device.unmute | A user is not allowed to unmute the device.| | constraint.password.unified | The managed profile is not allowed to have unified lock screen challenge with the primary user.| | constraint.autofill | A user is not allowed to use the autofill service.| | constraint.content.capture | Capturing the content of a user's screen is prohibited.| diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-particleAbility.md index e4499fb3d2..7955a810d3 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-particleAbility.md @@ -17,7 +17,7 @@ import particleAbility from '@ohos.ability.particleAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts a particle ability. This API uses an asynchronous callback to return the result. +Starts a Particle ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -26,7 +26,7 @@ Starts a particle ability. This API uses an asynchronous callback to return the | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -58,9 +58,9 @@ particleAbility.startAbility( ## particleAbility.startAbility -startAbility(parameter: StartAbilityParameter): Promise; +startAbility(parameter: StartAbilityParameter): Promise\; -Starts a particle ability. This API uses a promise to return the result. +Starts a Particle ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -69,7 +69,7 @@ Starts a particle ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| **Return value** @@ -107,7 +107,7 @@ particleAbility.startAbility( terminateSelf(callback: AsyncCallback\): void -Terminates this particle ability. This API uses an asynchronous callback to return the result. +Terminates this Particle ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -134,7 +134,7 @@ particleAbility.terminateSelf( terminateSelf(): Promise\ -Terminates this particle ability. This API uses a promise to return the result. +Terminates this Particle ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -188,7 +188,9 @@ particleAbility.acquireDataAbilityHelper(uri) startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void; -Requests a continuous task from the system. This API uses an asynchronous callback to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses an asynchronous callback to return the result. You are advised to use the new API [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8). + +**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -250,9 +252,11 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { startBackgroundRunning(id: number, request: NotificationRequest): Promise<void> +**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING + **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -Requests a continuous task from the system. This API uses a promise to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8-1). **Parameters** @@ -313,7 +317,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { cancelBackgroundRunning(callback: AsyncCallback<void>): void; -Requests to cancel a continuous task from the system. This API uses an asynchronous callback to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests to cancel a continuous task from the system. This API uses an asynchronous callback to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -344,7 +348,7 @@ particleAbility.cancelBackgroundRunning(callback); cancelBackgroundRunning(): Promise<void>; -Requests to cancel a continuous task from the system. This API uses a promise to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -380,9 +384,20 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](#want) | Yes | Service ability to connect.| +| request | [Want](js-apis-featureAbility.md#want) | Yes | Service ability to connect.| | options | ConnectOptions | Yes | Callback used to return the result. | + +ConnectOptions + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------ | ---- | -------- | ---- | ------------------------- | +| onConnect | Read only | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect | Read only | function | Yes | Callback invoked when the connection fails. | +| onFailed | Read only | function | Yes | Callback invoked when **connectAbility** fails to be called.| + **Example** ```js @@ -509,11 +524,8 @@ function onConnectCallback(element, remote){ Enumerates error codes. +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | -| INVALID_PARAMETER | -1 | Invalid parameter.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| - - - - - +| INVALID_PARAMETER | -1 | Invalid parameter.| diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md deleted file mode 100644 index 20f6b78599..0000000000 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ /dev/null @@ -1,17 +0,0 @@ -# PermissionRequestResult - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Provides the permission request result. - - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | 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. | diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 5e847795d0..ad79f05458 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -115,7 +115,7 @@ let result = plainArray.get(1); ### getIndexOfKey -getIndexOfKey(key: number): number; +getIndexOfKey(key: number): number Obtains the index of the first occurrence of an entry with the specified key in this container. @@ -143,7 +143,7 @@ let result = plainArray.getIndexOfKey("sdfs"); ### getIndexOfValue -getIndexOfValue(value: T): number; +getIndexOfValue(value: T): number Obtains the index of the first occurrence of an entry with the specified value in this container. @@ -171,7 +171,7 @@ let result = plainArray.getIndexOfValue("sddfhf"); ### getKeyAt -getKeyAt(index: number): number; +getKeyAt(index: number): number Obtains the key of the entry at the specified position in this container. @@ -238,7 +238,7 @@ Clones this container and returns a copy. The modification to the copy does not **Example** ``` -let plainArray = new ArrayList(); +let plainArray = new PlainArray(); plainArray.add(1, "sddfhf"); plainArray.add(2, "sffdfhf"); let newPlainArray = plainArray.clone(); @@ -416,7 +416,7 @@ plainArray.clear(); ### forEach -forEach(callbackfn: (value?: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object): void +forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -431,8 +431,8 @@ callbackfn | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| -| index | number | Yes| Key of the entry that is currently traversed.| -| plainArray | PlainArray | No| Instance that invokes the **forEach** API.| +| index | number | No| Key of the entry that is currently traversed.| +| PlainArray | PlainArray<T>| No| Instance that invokes the **forEach** API.| **Example** @@ -456,7 +456,7 @@ Obtains an iterator, each item of which is a JavaScript object. | Type| Description| | -------- | -------- | -| IterableIterator<[number, T]> | Iterator obtained.| +| IterableIterator<[number, T]> | Iterator obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index d3e6377b84..ca7e76cf6d 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -12,7 +12,7 @@ The Power Manager module provides APIs for rebooting and shutting down the syste import power from '@ohos.power'; ``` -## System Capabilities +## System Capability SystemCapability.PowerManager.PowerManager.Core @@ -25,7 +25,7 @@ Shuts down the system. This is a system API and cannot be called by third-party applications. -**Required permission:** ohos.permission.SHUTDOWN +**Required permission**: ohos.permission.REBOOT **Parameters** @@ -45,9 +45,9 @@ console.info('power_shutdown_device_test success') rebootDevice(reason: string): void -Restarts the device. +Reboots the system. -**Required permission:** ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_UPDATER (to reboot and enter the updater mode) +**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) **Parameters** @@ -71,7 +71,7 @@ Checks the screen status of the current device. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| @@ -94,10 +94,10 @@ isScreenOn(): Promise<boolean> Checks the screen status of the current device. -**Return Value** +**Return value** | Type | Description | | ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to asynchronously obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Promise<boolean> | Promise used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index 5306bc6697..29d055c83f 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,7 +1,7 @@ # ProcessRunningInfo > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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. Provides process running information. diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md new file mode 100644 index 0000000000..3b4523f4f2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -0,0 +1,272 @@ +# Prompt + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import prompt from '@ohos.prompt' +``` +## Required Permissions + +None. + +## prompt.showToast + +showToast(options: ShowToastOptions): void + +Shows the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| + +**Example** + ``` + export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } + } + ``` +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom | <length> | No | Distance between the toast border and the bottom of the screen. | + +## prompt.showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Example** + + ``` + export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ], + }) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) + } + } + ``` + +## prompt.showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void + +Shows a dialog box. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Example** + ``` + export default { + callback(err, data) { + if(err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }, + showDialog() { + prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ] + }, this.callback); + } + } + ``` + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| message | string | No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| + +## ShowDialogSuccessResponse + +Describes the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Description | +| ----- | ------ | ------------------- | +| index | number | Index of the selected button in the array.| + + +## prompt.showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + + +**Example** + ``` + export default { + callback(err, data) { + if(err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }, + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }, this.callback) + } + } + ``` + +## prompt.showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| + +**Return value** +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Example** + ``` + export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) + } + } + ``` +## ActionMenuOptions + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| buttons | Array | Yes | Array of menu items. The array structure is **{text:'button', color: '\#666666'}**. One to six items are supported. If there are more than six items, extra items will not be displayed.| + +## ActionMenuSuccessResponse + +Describes the action menu response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------------------ | +| index | number | No | Index of the selected button in the array, starting from **0**.| diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 543dcf5ea8..b773be3272 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -117,6 +117,7 @@ let result = queue.getFirst(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 86090ef47d..468091db60 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -173,7 +173,7 @@ Obtains the network selection mode of the SIM card in the specified slot. This A | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[NetworkSelectionMode](#networkselectionMode)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[NetworkSelectionMode](#networkselectionmode)\> | Yes | Callback used to return the result. | **Example** @@ -622,7 +622,7 @@ Defines the network registration status. | isRoaming | boolean | Whether the user is roaming.| | regState | [RegState](#regstate) | Network registration status of the device.| | cfgTech8+ | [RadioTechnology](#radiotechnology) | RAT of the device.| -| nsaState | [NsaState](#nsaState) | NSA network registration status of the device.| +| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.| | isCaActive | boolean | CA status.| | isEmergency | boolean | Whether only emergency calls are allowed.| diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index da7f0ae7bb..8d8b442bcf 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -11,30 +11,28 @@ import reminderAgent from'@ohos.reminderAgent'; ``` -## Required Permissions - -ohos.permission.PUBLISH_AGENT_REMINDER - - ## reminderAgent.publishReminder publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void Publishes an agent-powered reminder. This API uses an asynchronous callback to return the result. -- System capability +**Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent + +**Parameters** -- Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| -- Example +**Example** ``` - export default { data: {timer: { + export default { + data: { + timer: { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } @@ -53,23 +51,23 @@ publishReminder(reminderReq: ReminderRequest): Promise<number> Publishes an agent-powered reminder. This API uses a promise callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the published reminder's ID.| -- Example +**Example** ``` - export default { data: {timer: { + export default { + data: + {timer: { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } @@ -89,22 +87,21 @@ cancelReminder(reminderId: number, callback: AsyncCallback<void>): void Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { - cancel() { reminderAgent.cancelReminder(1, (err, data) => { + cancel() { + reminderAgent.cancelReminder(1, (err, data) => { console.log("do next"); }); } @@ -118,23 +115,21 @@ cancelReminder(reminderId: number): Promise<void> Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { @@ -153,17 +148,15 @@ getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| -- Example +**Example** ``` reminderAgent.getValidReminders((err, reminders) => { @@ -198,20 +191,18 @@ getValidReminders(): Promise<Array<ReminderRequest>> Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| -- Example +**Example** ``` -reminderAgent.getValidReminders().then((reminders) => { +reminderAgent.getValidReminders().then((reminders) => { for (let i = 0; i < reminders.length; i++) { console.log("getValidReminders = " + reminders[i]); console.log("getValidReminders, reminderType = " + reminders[i].reminderType); @@ -243,20 +234,18 @@ cancelAllReminders(callback: AsyncCallback<void>): void Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` -reminderAgent.cancelAllReminders((err, data) =>{ +reminderAgent.cancelAllReminders((err, data) =>{ console.log("do next")}) ``` @@ -267,17 +256,15 @@ cancelAllReminders(): Promise<void> Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` reminderAgent.cancelAllReminders().then(() => { @@ -291,18 +278,16 @@ addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>) Adds a reminder notification slot. This API uses an asynchronous callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { data: { mySlot: { @@ -324,23 +309,21 @@ addNotificationSlot(slot: NotificationSlot): Promise<void> Adds a reminder notification slot. This API uses a promise to return the result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { data: { mySlot: { @@ -362,18 +345,16 @@ removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback& Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { @@ -391,23 +372,21 @@ removeNotificationSlot(slotType: notification.SlotType): Promise<void> Removes a notification slot of a specified type. This API uses a promise to return the result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { @@ -423,7 +402,7 @@ export default { Enumerates button types. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Default Value| Description| | -------- | -------- | -------- | @@ -435,7 +414,7 @@ Enumerates button types. Enumerates reminder types. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Default Value| Description| | -------- | -------- | -------- | @@ -448,7 +427,7 @@ Enumerates reminder types. Defines a button displayed in the reminder notification. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -460,7 +439,7 @@ Defines a button displayed in the reminder notification. Sets the package and ability that are redirected to when the reminder notification is clicked. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -472,7 +451,7 @@ Sets the package and ability that are redirected to when the reminder notificati Sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -484,7 +463,7 @@ Sets the name of the target package and ability to start automatically when the Defines the reminder to publish. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -509,7 +488,7 @@ ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -524,9 +503,9 @@ ReminderRequestAlarm extends ReminderRequest Defines a reminder for an alarm. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -| Name| Type| Mandatory| Description:| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| @@ -539,7 +518,7 @@ ReminderRequestTimer extends ReminderRequest Defines a reminder for a scheduled timer. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -550,7 +529,7 @@ Defines a reminder for a scheduled timer. Sets the time information for a calendar reminder. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index e5e0509263..19572a3c96 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -19,9 +19,9 @@ Obtains the **ResourceManager** object of this application. This method uses a c **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------- | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| **Example** ``` @@ -50,10 +50,10 @@ Obtains the **ResourceManager** object of an application. This method uses an as **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | --------- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application. | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------- | +| bundleName | string | Yes | Bundle name of the target application. | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| **Example** ``` @@ -71,9 +71,9 @@ Obtains the **ResourceManager** object of this application. This method uses a p **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained. | +| Type | Description | +| ---------------------------------------- | ----------------- | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| **Example** ``` @@ -100,14 +100,14 @@ Obtains the **ResourceManager** object of an application. This method uses a pro **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | --------- | -------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| bundleName | string | Yes | Bundle name of the target application.| **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained. | +| Type | Description | +| ---------------------------------------- | ------------------ | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| **Example** ``` @@ -125,10 +125,10 @@ Enumerates the screen directions. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------------- | ------------- | ----------- | -| DIRECTION_VERTICAL | 0 | Portrait | -| DIRECTION_HORIZONTAL | 1 | Landscape | +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DIRECTION_VERTICAL | 0 | Portrait | +| DIRECTION_HORIZONTAL | 1 | Landscape | ## DeviceType @@ -137,14 +137,14 @@ Enumerates the device types. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------------- | ------------- | ------------- | -| DEVICE_TYPE_PHONE | 0x00 | Mobile phone. | -| DEVICE_TYPE_TABLET | 0x01 | Tablet. | -| DEVICE_TYPE_CAR | 0x02 | Automobile. | -| DEVICE_TYPE_PC | 0x03 | Computer. | -| DEVICE_TYPE_TV | 0x04 | TV. | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DEVICE_TYPE_PHONE | 0x00 | Mobile phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Automobile. | +| DEVICE_TYPE_PC | 0x03 | Computer. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -153,14 +153,14 @@ Enumerates the screen density types. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------- | ------------- | ---------------------------------------- | -| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI). | -| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI). | -| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI). | -| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI). | -| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI). | -| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). | +| Name | Default Value | Description | +| -------------- | ---- | ---------- | +| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI). | +| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI). | +| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI). | +| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI). | +| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI). | +| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).| ## Configuration @@ -170,10 +170,10 @@ Defines the device configuration. **System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Readable | Writable | Description | -| --------- | ----------------------- | -------- | -------- | ------------------------------- | -| direction | [Direction](#direction) | Yes | No | Screen direction of the device. | -| locale | string | Yes | No | Current system language. | +| Name | Type | Readable | Writable | Description | +| --------- | ----------------------- | ---- | ---- | -------- | +| direction | [Direction](#direction) | Yes | No | Screen direction of the device.| +| locale | string | Yes | No | Current system language. | ## DeviceCapability @@ -183,10 +183,10 @@ Defines the device capability. **System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Readable | Writable | Description | -| ------------- | ------------------------------- | -------- | -------- | ----------------------------- | -| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | +| Name | Type | Readable | Writable | Description | +| ------------- | ------------------------------- | ---- | ---- | -------- | +| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | ## RawFileDescriptor8+ @@ -194,11 +194,11 @@ Defines the device capability. Defines the descriptor information of the raw file.
**System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Description | -| ------ | ------ | ---------------------------------------- | -| fd | number | Descriptor of a raw file. | -| offset | number | Offset to the start position of the raw file. | -| length | number | Length of the raw file. | +| Name | Type | Description | +| ------ | ------ | ------------------ | +| fd | number | Descriptor of a raw file.| +| offset | number | Offset to the start position of the raw file. | +| length | number | Length of the raw file. | ## ResourceManager @@ -220,10 +220,10 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the string obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the string obtained.| **Example** ``` @@ -248,14 +248,14 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the string obtained. | +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | Promise used to return the string obtained.| **Example** ``` @@ -278,10 +278,10 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the obtained array of strings. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the obtained array of strings.| **Example** ``` @@ -306,14 +306,14 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ---------------------------------- | ---------------------------------------- | -| Promise<Array<string>> | Promise used to return the array of strings obtained. | +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the array of strings obtained.| **Example** ``` @@ -336,10 +336,10 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the content of the media file obtained. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the content of the media file obtained.| **Example** ``` @@ -364,14 +364,14 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ---------------------------------------- | -| Promise<Uint8Array> | Promise used to return the content of the media file obtained. | +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| **Example** ``` @@ -394,10 +394,10 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the Base64 code of the image obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the Base64 code of the image obtained.| **Example** ``` @@ -422,14 +422,14 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the Base64 code of the image obtained. | +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the Base64 code of the image obtained.| **Example** ``` @@ -452,9 +452,9 @@ Obtains the device configuration. This method uses an asynchronous callback to r **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the obtained device configuration. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the obtained device configuration.| **Example** ``` @@ -479,9 +479,9 @@ Obtains the device configuration. This method uses a promise to return the resul **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the device configuration. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| **Example** ``` @@ -504,9 +504,9 @@ Obtains the device capability. This method uses an asynchronous callback to retu **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the obtained device capability. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the obtained device capability.| **Example** ``` @@ -531,9 +531,9 @@ Obtains the device capability. This method uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability. | +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| **Example** ``` @@ -556,11 +556,11 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number that determines the plural or singular form. | -| callback | AsyncCallback<string> | Yes | Callback used to return the singular-plural string obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | Yes | Resource ID. | +| num | number | Yes | Number that determines the plural or singular form. | +| callback | AsyncCallback<string> | Yes | Callback used to return the singular-plural string obtained.| **Example** ``` @@ -585,15 +585,15 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number that determines the plural or singular form. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| num | number | Yes | Number that determines the plural or singular form. | **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the singular-plural string obtained. | +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the singular-plural string obtained.| **Example** ``` @@ -615,10 +615,10 @@ Obtains the content of the raw file in the specified path. This method uses an a **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ---------------------------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the raw file content, in byte arrays. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the raw file content, in byte arrays.| **Example** ``` @@ -642,14 +642,14 @@ Obtains the content of the raw file in the specified path. This method uses a pr **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | --------------------- | -| path | string | Yes | Path of the raw file. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| **Return value** -| Type | Description | -| ------------------------- | ---------------------------------------- | -| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays. | +| Type | Description | +| ------------------------- | ----------- | +| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| **Example** ``` @@ -671,10 +671,10 @@ Obtains the descriptor of the raw file in the specified path. This method uses a **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8+ ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. + +## Modules to Import + +``` +import router from '@ohos.router' +``` + +## Required Permissions + +None. + +## router.push + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Page routing parameters.| + + +**Example** + ``` + // Current page + export default { + pushPage() { + router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } + } + ``` + ``` + // routerpage2 page + export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } + } + ``` + + +## router.replace + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Description of the new page.| + +**Example** + ``` + // Current page + export default { + replacePage() { + router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + ``` + + ``` + // detail page + export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } + } + ``` + +## router.back + +back(options?: RouterOptions ): void + +Returns to the previous page or a specified page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.| + +**Example** + ``` + // index page + export default { + indexPushPage() { + router.push({ + url: 'pages/detail/detail', + }); + } + } + ``` + + ``` + // detail page + export default { + detailPushPage() { + router.push({ + url: 'pages/mall/mall', + }); + } + } + ``` + + ``` + // Navigate from the mall page to the detail page through router.back(). + export default { + mallBackPage() { + router.back(); + } + } + ``` + + ``` + // Navigate from the detail page to the index page through router.back(). + export default { + defaultBack() { + router.back(); + } + } + ``` + + ``` + // Return to the detail page through router.back(). + export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } + } + ``` + +## router.clear + +clear(): void + +Clears all historical pages in the stack and retains only the current page at the top of the stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + ``` + export default { + clearPage() { + router.clear(); + } + } + ``` + +## router.getLength + +getLength(): string + +Obtains the number of pages in the current stack. + +**Return value** + | Type| Description| + | -------- | -------- | + | string | Number of pages in the stack. The maximum value is **32**.| + +**Example** + ``` + export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } + } + ``` + +## router.getState + +getState(): RouterState + +Obtains state information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| [RouterState](#routerstate) | Page routing state.| +## RouterState +Describes the page routing state. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + | Name| Type| Description| + | -------- | -------- | -------- | + | index | number | Index of the current page in the stack.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The index starts from 1 from the bottom to the top of the stack.| + | name | string | Name of the current page, that is, the file name.| + | path | string | Path of the current page.| + +**Example** + ``` + export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } + } + ``` + +## router.enableAlertBeforeBackPage + +enableAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [EnableAlertOptions](#enablealertoptions) | Yes| Description of the dialog box.| + +**Example** + + ``` + export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` +## EnableAlertOptions + +Describes the confirm dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| message | string | Yes| Content displayed in the confirm dialog box.| + +## router.disableAlertBeforeBackPage + +disableAlertBeforeBackPage(): void + +Disables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + ``` + export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage(); + } + } + ``` + +## router.getParams + +getParams(): Object + +Obtains the parameters passed from the page that initiates redirection to the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| Object | Parameters passed from the page that initiates redirection to the current page.| + +**Example** + +- Web-like example + ``` + // Current page + export default { + pushPage() { + router.push({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + ``` + ``` + // detail page + export default { + onInit() { + console.info('showData1:' + router.getParams().data1); + } + } + ``` + +- Declarative example + + ``` + // Navigate to the target page through router.push with the params parameter carried. + import router from '@ohos.router' + + @Entry + @Component + struct Index { + async routePage() { + let options = { + url: 'pages/second', + params: { + text: 'This is the value on the first page.', + data: { + array: [12, 45, 78] + }, + } + } + try { + await router.push(options) + } catch (err) { + console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`) + } + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('This is the first page.') + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { + this.routePage() + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ``` + // Receive the transferred parameters on the second page. + import router from '@ohos.router' + + @Entry + @Component + struct Second { + private content: string = "This is the second page." + @State text: string = router.getParams().text + @State data: any = router.getParams().data + @State secondData : string = '' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(`${this.content}`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Text(this.text) + .fontSize(30) + .onClick(()=>{ + this.secondData = (this.data.array[1]).toString() + }) + .margin({top:20}) + Text('Value from the first page '+'' + this.secondData) + .fontSize(20) + .margin({top:20}) + .backgroundColor('red') + } + .width('100%') + .height('100%') + } + } + ``` + +## RouterOptions + +Describes the page routing options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| URI of the destination page, in either of the following formats:
-  Absolute path of the page. The value is available in the pages list in the config.json file, for example:
  - pages/index/index
  - pages/detail/detail
-  Particular path. If the URI is a slash (/), the home page is displayed.| +| params | Object | No| Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| + + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > The page routing stack supports a maximum of 32 pages. diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index b2d01bd6da..4a9ba2ab23 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -107,16 +107,16 @@ Creates a **RunningLock** object. **Example** ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - var used = runninglock.isUsed(); - console.info('runninglock is used: ' + used); - runninglock.lock(500); - used = runninglock.isUsed(); - console.info('after lock runninglock is used ' + used); -}) -.catch(error => { - console.log('create runningLock test error: ' + error); +runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { + if (typeof error === "undefined") { + console.log('create runningLock test error: ' + error); + } else { + var used = lockIns.isUsed(); + console.info('runninglock is used: ' + used); + lockIns.lock(500); + used = lockIns.isUsed(); + console.info('after lock runninglock is used ' + used); + } }) ``` @@ -170,11 +170,13 @@ Locks and holds a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core +**Required permission:** ohos.permission.RUNNING_LOCK + **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | -------------------- | -| timeout | number | No | Duration for locking and holding the **RunningLock** object.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | -------------------------- | +| timeout | number | No | Duration for locking and holding the **RunningLock** object, in ms.| **Example** @@ -185,7 +187,7 @@ runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.B console.info('create runningLock success') }) .catch(error => { - console.log('Lock runningLock test error: ' + error) + console.log('create runningLock test error: ' + error) }); ``` @@ -198,16 +200,18 @@ Releases a **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core +**Required permission:** ohos.permission.RUNNING_LOCK + **Example** ``` runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) .then(runningLock => { runningLock.unlock() - console.info('unLock runningLock success') + console.info('create and unLock runningLock success') }) .catch(error => { - console.log('unLock runningLock test error: ' + error) + console.log('create runningLock test error: ' + error) }); ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index b163b58eb4..6164de2a46 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -22,14 +22,14 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); @@ -51,14 +51,14 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal **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.| +**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. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); @@ -80,14 +80,14 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -110,14 +110,14 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); @@ -139,14 +139,14 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); @@ -168,14 +168,14 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -198,14 +198,14 @@ Subscribes to data changes of the significant motion sensor. If this API is call **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); @@ -225,14 +225,14 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); @@ -252,14 +252,14 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); @@ -277,14 +277,14 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); @@ -302,14 +302,14 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); @@ -323,20 +323,20 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options: Options): void +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. **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -359,14 +359,14 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); @@ -384,14 +384,14 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); @@ -409,14 +409,14 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); @@ -434,14 +434,14 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); @@ -459,14 +459,14 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); @@ -484,14 +484,14 @@ Subscribes to data changes of the orientation sensor. If this API is called mult **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ console.info('The device rotates at an angle around the X axis: ' + data.beta); @@ -512,14 +512,14 @@ Subscribes to only one data change of the heart rate sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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**.| -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ @@ -537,14 +537,14 @@ Subscribes to data changes of the rotation vector sensor. If this API is called **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); @@ -565,14 +565,14 @@ Subscribes to data changes of the wear detection sensor. If this API is called m **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.| +**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 +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); @@ -592,13 +592,13 @@ Subscribes to only one data change of the acceleration 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**.| - | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes| One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); @@ -619,13 +619,13 @@ Subscribes to only one data change of the linear acceleration 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_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**.| +**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**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); @@ -646,13 +646,13 @@ Subscribes to only one data change of the uncalibrated acceleration 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| One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -674,13 +674,13 @@ Subscribes to only one data change of the gravity 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| One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); @@ -701,13 +701,13 @@ Subscribes to only one data change of the gyroscope 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**.| - | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); @@ -728,13 +728,13 @@ Subscribes to only one data change of the uncalibrated gyroscope 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| One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -756,13 +756,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); @@ -781,13 +781,13 @@ Subscribes to only one data change of the pedometer 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); @@ -806,13 +806,13 @@ Subscribes to only one data change of the pedometer 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| One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); @@ -829,13 +829,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); @@ -852,13 +852,13 @@ Subscribes to only one data change 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| One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); @@ -877,13 +877,13 @@ Subscribes to only one data change 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| One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -905,13 +905,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { @@ -932,13 +932,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { console.info('Humidity: ' + data.humidity); @@ -955,13 +955,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { console.info('Atmospheric pressure: ' + data.pressure); @@ -978,13 +978,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { console.info('Status: ' + data.status); @@ -1001,13 +1001,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { console.info(' Illumination: ' + data.intensity); @@ -1024,13 +1024,13 @@ Subscribes to only one data change of the orientation 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| One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); @@ -1049,13 +1049,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); @@ -1077,13 +1077,13 @@ Subscribes to only one data change of the heart rate 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**.| +**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**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { console.info("Heart rate: " + data.heartRate); @@ -1100,13 +1100,13 @@ Subscribes to only one data change 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_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**.| +**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 +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { console.info("Wear status: "+ data.value); @@ -1124,14 +1124,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1152,14 +1152,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1181,14 +1181,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1205,14 +1205,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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**.| +| 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 +**Example** ``` function callback(data) { @@ -1229,14 +1229,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1253,14 +1253,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1281,14 +1281,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1301,7 +1301,7 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeResponse>): void +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void Unsubscribes from sensor data changes. @@ -1309,14 +1309,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1335,14 +1335,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1361,14 +1361,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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**.| -- Example +**Example** ``` function callback(data) { @@ -1387,14 +1387,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1413,14 +1413,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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**.| -- Example +**Example** ``` function callback(data) { @@ -1441,14 +1441,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1467,14 +1467,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1496,14 +1496,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1522,14 +1522,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Return value** ``` function callback(data) { @@ -1548,14 +1548,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1572,14 +1572,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1596,14 +1596,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1623,14 +1623,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function callback(data) { @@ -1647,14 +1647,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | [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 +**Example** ``` function accCallback(data) { @@ -1671,29 +1671,28 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| ---------------- | ---------------------------------------- | ---- | ----------- | +| 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 - - ``` - sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':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.x); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }) - ``` +**Example** +``` +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':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.x); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }) +``` ## sensor.transformCoordinateSystem transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> @@ -1702,35 +1701,32 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **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 +**Parameters** - | Type | Description | - | ---------------------------------- | ---------------------- | - | Promise<Array<number>> | Promise used to return the rotation vector after being converted.| +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------------- | ---- | -------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| -- Example +**Return value** - ``` - const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':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"); - }) - ``` +| Type | Description | +| ---------------------------------- | ----------- | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| - +**Example** +``` +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':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 @@ -1740,27 +1736,25 @@ Obtains the geomagnetic field of a geographic location. This API uses a callback **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 - ``` - sensor.getGeomagneticField([80, 0, 0], {'timeMillis':1580486400000}, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - 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); - }); - ``` - +**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** +``` +sensor.getGeomagneticField([80, 0, 0], 1580486400000, function(err, data) { + if (err) { + console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + 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); +}); +``` ## sensor.getGeomagneticField getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> @@ -1769,20 +1763,20 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **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.| +**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.| +**Return value** +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| -- Example +**Return value** ``` - const promise = sensor.getGeomagneticField([80, 0, 0], {'timeMillis':1580486400000}); + const promise = sensor.getGeomagneticField([80, 0, 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 + @@ -1800,15 +1794,15 @@ Obtains the altitude at which the device is located based on the sea-level atmos **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------- | --------------------------- | ---- | ------------------------------------- | - | seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | - | currentPressure | number | Yes | Current 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 | +| --------------- | --------------------------- | ---- | -------------------- | +| 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 +**Return value** ``` sensor.getAltitude(0, 200, function(err, data) { @@ -1829,20 +1823,20 @@ Obtains the altitude at which the device is located based on the sea-level atmos **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| --------------- | ------ | ---- | -------------------- | +| 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 +**Return value** - | Type | Description | - | --------------------- | ------------------------------------ | - | Promise<number> | Promise used to return the altitude, in meters.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the altitude, in meters.| -- Example +**Return value** ``` const promise = sensor.getAltitude(0, 200); @@ -1862,14 +1856,14 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| ----------------- | --------------------------- | ---- | -------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| -- Example +**Return value** ``` sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { @@ -1878,7 +1872,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba err.message); return; } - console.info(Successed to get getGeomagneticDip interface get data: " + data); + console.info("Successed to get getGeomagneticDip interface get data: " + data); }) ``` @@ -1890,19 +1884,19 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ----------------- | ------------------- | ---- | -------------- | - | inclinationMatrix | Array<number> | Yes | Inclination matrix.| +| Name | Type | Mandatory | Description | +| ----------------- | ------------------- | ---- | ------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix.| -- Return value +**Return value** - | Type | Description | - | --------------------- | ---------------------------- | - | Promise<number> | Promise used to return the magnetic dip, in radians.| +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians.| -- Example +**Return value** ``` const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); @@ -1921,15 +1915,15 @@ Obtains the angle change between two rotation matrices. This API uses a callback **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| --------------------- | ---------------------------------------- | ---- | ------------------ | +| 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 +**Return value** ``` 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) { @@ -1954,20 +1948,20 @@ Obtains the angle change between two rotation matrices. This API uses a promise **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------------- | ------------------- | ---- | ------------------ | - | currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| - | preRotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory | Description | +| --------------------- | ------------------- | ---- | --------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| +| preRotationMatrix | Array<number> | Yes | Rotation matrix. | -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | --------------------------------- | - | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | ------------------ | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| -- Example +**Return value** ``` 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]); @@ -1990,14 +1984,14 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| -------------- | ---------------------------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| -- Example +**Return value** ``` sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { @@ -2022,19 +2016,19 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | -------------- | - | Promise<Array<number>> | Promise used to return the rotation matrix.| +| Type | Description | +| ---------------------------------- | ------- | +| Promise<Array<number>> | Promise used to return the rotation matrix.| -- Example +**Return value** ``` const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); @@ -2057,14 +2051,14 @@ Converts a rotation vector into a quaternion. This API uses a callback to return **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| -------------- | ---------------------------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | -- Example +**Return value** ``` sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { @@ -2089,19 +2083,19 @@ Converts a rotation vector into a quaternion. This API uses a promise to return **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | ------------ | - | Promise<Array<number>> | Promise used to return the quaternion.| +| Type | Description | +| ---------------------------------- | ------ | +| Promise<Array<number>> | Promise used to return the quaternion.| -- Example +**Return value** ``` const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); @@ -2124,14 +2118,14 @@ Obtains the device direction based on the rotation matrix. This API uses a callb **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| -------------- | ---------------------------------------- | ---- | ------------------ | +| 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 +**Return value** ``` sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { @@ -2156,19 +2150,19 @@ Obtains the device direction based on the rotation matrix. This API uses a promi **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix.| -- Return value +**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 angle around the z, x, and y axes.| -- Example +**Return value** ``` const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); @@ -2191,15 +2185,15 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 | +| ----------- | ---------------------------------------- | ---- | ------- | +| 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 +**Return value** ``` sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { @@ -2224,20 +2218,20 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**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 +**Return value** - | Type | Description | - | ------------------------------------------------------------ | -------------- | - | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| -- Example +**Return value** ``` const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); @@ -2259,29 +2253,29 @@ 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_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.| +| 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 @@ -2290,9 +2284,9 @@ Describes the timestamp of the sensor data. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| timestamp | number | Yes| Yes| Timestamp when the sensor reports data.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------------ | +| timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| ## AccelerometerResponse @@ -2302,11 +2296,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 @@ -2316,11 +2310,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 @@ -2330,14 +2324,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 @@ -2347,11 +2341,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 @@ -2361,11 +2355,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 rad.| -| beta | number | Yes| Yes| Rotation angle of the device around the x-axis, in rad.| -| gamma | number | Yes| Yes| Rotation angle of the device around the y-axis, in rad.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ------------------------ | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in rad.| +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in rad. | +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in rad. | ## RotationVectorResponse @@ -2375,12 +2369,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 @@ -2390,11 +2384,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 @@ -2404,14 +2398,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 @@ -2421,9 +2415,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 @@ -2433,9 +2427,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 @@ -2445,9 +2439,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 @@ -2457,9 +2451,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| status | number | Yes| Yes| Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | --------------------------------- | +| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| ## MagneticFieldResponse @@ -2469,11 +2463,11 @@ Describes the magnetic field sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Magnetic field strength on the x-axis, in μT.| -| y | number | Yes| Yes| Magnetic field strength on the y-axis, in μT.| -| z | number | Yes| Yes| Magnetic field strength on the z-axis, in μT.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------------------ | +| x | number | Yes | Yes | Magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Magnetic field strength on the z-axis, in μT.| ## MagneticFieldUncalibratedResponse @@ -2483,14 +2477,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 @@ -2500,9 +2494,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 @@ -2512,9 +2506,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 @@ -2524,9 +2518,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 @@ -2536,9 +2530,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 @@ -2548,9 +2542,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 @@ -2560,9 +2554,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 @@ -2572,9 +2566,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 @@ -2583,8 +2577,8 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Description| -| -------- | -------- | -------- | +| Name | Type | Description | +| -------- | ------ | --------------------------- | | interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| ## RotationMatrixResponse @@ -2593,10 +2587,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 @@ -2605,10 +2599,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 @@ -2617,15 +2611,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 @@ -2633,8 +2627,8 @@ 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.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-service-extension-ability.md deleted file mode 100644 index c78d82cad4..0000000000 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ /dev/null @@ -1,161 +0,0 @@ -# ServiceExtensionAbility - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Provides APIs related to **ServiceExtension**. - - -## Modules to Import - -``` -import ServiceExtension from '@ohos.application.ServiceExtensionAbility'; -``` - - -## Required Permissions - -None. - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service extension context, which is inherited from **ExtensionContext**.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## ServiceExtensionAbility.onCreate - -onCreate(want: Want): void; - -Called when an extension is created to initialize the service logic. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onDestroy - -onDestroy(): void; - -Called when this extension is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## ServiceExtensionAbility.onRequest - -onRequest(want: Want, startId: number): void; - -Called after **onCreate** is invoked when an ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onConnect - -onConnect(want: Want): rpc.RemoteObject; - -Called after **onCreate** is invoked when an ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| - -**Example** - - ```js - import rpc from '@ohos.rpc' - class StubTest extends rpc.RemoteObject{ - constructor(des) { - super(des); - } - onRemoteRequest(code, data, reply, option) { - } - } - class ServiceExt extends ServiceExtension { - onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); - } - } - ``` - - -## ServiceExtensionAbility.onDisconnect - -onDisconnect(want: Want): void; - -Called when the ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index ce5ab6b95a..0c6b7c6749 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -1,7 +1,7 @@ # ServiceExtensionContext > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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. Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index b5e1886715..b3908e1f7a 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -350,7 +350,7 @@ Obtains the status of the SIM card in the specified slot. This API uses an async | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[SimState](#simState)\> | Yes | Callback used to return the result. For details, see [SimState](#simState). | +| callback | AsyncCallback\<[SimState](#simstate)\> | Yes | Callback used to return the result. For details, see [SimState](#simState). | **Example** @@ -379,7 +379,7 @@ Obtains the status of the SIM card in the specified slot. This API uses a promis | Type | Description | | -------------------------------- | ------------------------------------------ | -| Promise\<[SimState](#simState)\> | Promise used to return the result.| +| Promise\<[SimState](#simstate)\> | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 2cec7c7cc3..3a8edec816 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -145,6 +145,7 @@ let result = stack.locate(2); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void @@ -179,6 +180,7 @@ stack.forEach((value, index) => { ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entries). 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 66b51201e3..7c2fcf4944 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - This is a system API and cannot be called by third-party applications. +> - The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -125,4 +125,3 @@ Asynchronously obtains the available space of the specified volume. This method console.info("getFreeSizeOfVolume successfully:"+ number); }); ``` - diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md new file mode 100644 index 0000000000..db1fc9a0e0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -0,0 +1,214 @@ +# Application Context + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. +> +> - 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. + + +## Modules to Import + + +``` +import app from '@system.app'; +``` + + +## app.getInfo + +getInfo(): AppResponse + +Obtains the declared information in the **config.json** file of an application. + +> **Note: ** [`@ohos.bundle`](js-apis-Bundle.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Return value** + +| Type| Description| +| -------- | -------- | +| [AppResponse](#appresponse) | Application response information.| + +**Example** + + ``` + export default { + getInfo(){ + var info = app.getInfo(); + console.log(JSON.stringify(info)); + } + } + ``` + +## app.terminate + +terminate(): void + +Terminates the current ability. + +> **Note: ** [`@ohos.ability.featureAbility`](js-apis-featureAbility.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Example** + + ``` + export default { + terminate(){ + app.terminate(); + }} + ``` +## app.requestFullWindow + +requestFullWindow(options?: RequestFullWindowOptions): void + +Requests the application to run in full window. You can call this API when the FA runs in a non-full window, for example, semi-modal FA. This API is invalid for an application already in full-window mode. + +This is a system API and cannot be called by third-party applications. + +> **Note: ** [`@ohos.window`](js-apis-window.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [RequestFullWindowOptions](#requestfullwindowoptions) | No| Duration for transition from the non-full window to the full window, in milliseconds. By default, the value is in direct proportion to the distance between the non-full window and the full window.| + +**Example** + + ``` + export default { + requestFullWindow(){ + app.requestFullWindow({ + duration: 200}); + } + } + ``` + +## app.setImageCacheCount7+ + +setImageCacheCount(value: number): void + +Sets the maximum number of decoded images that can be cached in the memory to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The built-in Least Recently Used (LRU) policy is used for caching. If the maximum number is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the number of images is too large, the memory usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Number of decoded images that are cached in the memory.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## app.setImageRawDataCacheSize7+ + +setImageRawDataCacheSize(value: number): void + +Sets the maximum size (in bytes) of the image data cached in the memory before decoding to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the memory usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Size of the image data cached before decoding, in bytes.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageRawDataCacheSize(104,857,600) // Set the upper limit of the memory for caching image data before decoding to 100 MB. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## app.setImageFileCacheSize7+ + +setImageFileCacheSize(value: number): void + +Sets the maximum size of the image file cache (in bytes) to speed up the loading of images from the same sources, especially online image sources and thumbnails. If the input parameter is not set, the default value 100 MB is used. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the disk usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Size of the image file cache, in bytes.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageFileCacheSize(209,715,200) // Set the upper limit of the image file cache to 200 MB. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## AppResponse + +Defines the application response information. + +**System capability**: The items in the table below require different system capabilities. For details, see the table. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- |-------- | +| appID6+ | string | Yes| Bundle name of an application. It uniquely identifies the application.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| appName | string | Yes| Application name.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| versionName | string | Yes| Application version name.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| versionCode | number | Yes| Application version number.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| + +## ScreenOnVisibleOptions + +Defines the options of the visible interface on the screen. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| visible | boolean | No| Whether to keep the application visible. The default value is **false**.| +| success | () => void | No| Callback upon success.| +| fail | (data: string, code: number) => void | No| Callback upon failure.| +| complete | () => void | No| Called when the API call is complete.| + +## RequestFullWindowOptions + +Defines the options of the **RequestFullWindow** API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| duration | number | Yes| Number of animation options.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md new file mode 100644 index 0000000000..c65bc13c40 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -0,0 +1,55 @@ +# Battery Level + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import battery from '@system.battery'; +``` + + +## battery.getStatus + +getStatus(Object): void + +Obtains the current charging state and battery level. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +**Parameter** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the check result is obtained | +| fail | Function | No | Called when the check result fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the check result is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged | +| level | number | Current battery level, which ranges from 0.00 to 1.00. | + +**Example** + +``` +export default { + getStatus() { + battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.log('fail to get battery level code:' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md new file mode 100644 index 0000000000..ce21ce2e7c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -0,0 +1,202 @@ +# Screen Brightness + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import brightness from '@system.brightness'; +``` + + +## brightness.getValue + +getValue(Object): void + +Obtains the current screen brightness. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Name | Type | Description | +| -------- | -------- | -------- | +| value | number | Screen brightness, which ranges from 1 to 255. | + +**Example** + +``` +export default { + getValue() { + brightness.getValue({ + success: function(data){ + console.log('success get brightness value:' + data.value); + }, + fail: function(data, code) { + console.log('get brightness fail, code: ' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setValue + +setValue(Object): void + +Sets the screen brightness. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| value | number | Yes | Screen brightness. The value is an integer ranging from 1 to 255.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used. | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setValue() { + brightness.setValue({ + value: 100, + success: function(){ + console.log('handling set brightness success.'); + }, + fail: function(data, code){ + console.log('handling set brightness value fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.getMode + +getMode(Object): void + +Obtains the screen brightness adjustment mode. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Name | Type | Description | +| -------- | -------- | -------- | +| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | + +**Example** + +``` +export default { + getMode() { + brightness.getMode({ + success: function(data){ + console.log('success get mode:' + data.mode); + }, + fail: function(data, code){ + console.log('handling get mode fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setMode + +setMode(Object): void + +Sets the screen brightness adjustment mode. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| mode | number | Yes | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setMode() { + brightness.setMode({ + mode: 1, + success: function(){ + console.log('handling set mode success.'); + }, + fail: function(data, code){ + console.log('handling set mode fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setKeepScreenOn + +setKeepScreenOn(Object): void + +Sets whether to always keep the screen on. Call this API in **onShow()**. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| keepScreenOn | boolean | Yes | Whether to always keep the screen on | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setKeepScreenOn() { + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.') + }, + fail: function (data, code) { + console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md new file mode 100644 index 0000000000..b0dc3c5b11 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -0,0 +1,165 @@ +# Encryption Algorithm + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> +> - 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. +> - This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. + + +## Modules to Import + + +``` +import cipher from '@system.cipher' +``` + + +## cipher.rsa + +rsa(Object): void + +Encrypts or decrypts data using RSA. + +**System capability**: SystemCapability.Security.Cipher + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | +| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | +| key | string | Yes | Keys encrypted using RSA. During encryption, this parameter is a public key. During decryption, it is a private key. | +| transformation | string | No | RSA algorithm padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**. | +| success | Function | No | Called when data is encrypted or decrypted successfully. | +| fail | Function | No | Called when data fails to be encrypted or decrypted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + rsa() { + cipher.rsa({ + // Encrypt data. + action: 'encrypt', + // Text content to be encrypted + text: 'hello', + // Base64-encoded public key used for encryption + key: + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + + 'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + + 'h7SoaYEeluhqFimL2AEjfSwINHCLqObJkcjCfoZpE1JCehPiDOJsyT50Auc08h/4\n' + + 'jHQfanyC1nc62LqUCQIDAQAB', + success: function(data) { + console.log('handling success: ${data.text}'); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}: ${data}`); + } + }); + cipher.rsa({ + // Decrypt data. + action: 'decrypt', + // The text to be decrypted is a Base64-encoded binary value, and the decrypted text is "hello". + text: + 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + + 'S/ZWNI4Q8Q0suNjNkGU=', + // Base64-encoded public key used for encryption + key: + 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + + '7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + + 'aXHFEK1xQ3+HtKhpgR6W6GoWKYvYASN9LAg0cIuo5smRyMJ+hmkTUkJ6E+IM4mzJ\n' + + 'PnQC5zTyH/iMdB9qfILWdzrYupQJAgMBAAECgYEAkibhH0DWR13U0gvYJeD08Lfd\n' + + 'Sw1PMHyquEqIcho9Yv7bF3LOXjOg2EEGPx09mvuwXFgP1Kp1e67XPytr6pQQPzK7\n' + + 'XAPcLPx80R/ZjZs8vNFndDOd1HgD3vSVmYQarNzmKi72tOUWMPevsaFXPHo6Xx3X\n' + + '8x0wYb7XuBsQguRctTECQQD7GWX3JUiyo562iVrpTDPOXsrUxmzCrgz2OZildxMd\n' + + 'Pp/PkyDrx7mEXTpk4K/XnQJ3GpJNi2iDSxDuPSAeJ/aPAkEA4Tw4+1Z43S/xH3C3\n' + + 'nfulYBNyB4si6KEUuC0krcC1pDJ21Gd12efKo5VF8SaJI1ZUQOzguV+dqNsB/JUY\n' + + 'OFfX5wJAB1dKv9r7MR3Peg6x9bggm5vx2h6i914XSuuMJupASM6X5X2rrLj+F3yS\n' + + 'RHi9K1SPyeOg+1tkBtKfABgRZFBOyQJAbuTivUSe73AqTKuHjB4ZF0ubqgEkJ9sf\n' + + 'Q2rekzm9dOFvxjZGPQo1qALX09qATMi1ZN376ukby8ZAnSafLSZ64wJBAM2V37go\n' + + 'Sj44HF76ksRow8gecuQm48NCTGAGTicXg8riKog2GC9y8pMNHAezoR9wXJF7kk+k\n' + + 'lz5cHyoMZ9mcd30=', + success: function(data) { + console.log('handling success: ${data.text}'); + }, + fail: function(data, code) { + console.log(`### cipher.rsa decrypt fail ### ${code}: ${data}`); + }, + }); + } +} +``` + + +## cipher.aes + +aes(Object): void + +Encrypts or decrypts data using AES. + +**System capability**: SystemCapability.Security.Cipher + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | +| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text. The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | +| key | string | Yes | Key used for encryption or decryption, which is a character string encrypted using Base64. | +| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | +| iv | string | No | Initial vector for AES-based encryption and decryption. The value is a character string encoded using Base64. The default value is the key value. | +| ivOffset | string | No | Offset of the initial vector for AES-based encryption and decryption. The default value is **0**. | +| ivLen | string | No | Length of the initial vector for AES-based encryption and decryption. The default value is **16**. | +| success | Function | No | Called when data is encrypted or decrypted successfully. | +| fail | Function | No | Called when data fails to be encrypted or decrypted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + aes() { + cipher.aes({ + // Encrypt data. + action: 'encrypt', + // Text content to be encrypted + text: 'hello', + // Base64-encoded key used for encryption + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: 0, + ivLen: 16, + success: (data) => { + console.log('handling success: ${data.text}'); + }, + fail: (data, code) => { + console.log(`### cipher.aes encrypt fail ### ${code}: ${data}`); + } + }); + cipher.aes({ + // Decrypt data. + action: 'decrypt', + // Text to be decrypted, which is a Base64-encoded binary value + text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + + 'S/ZWNI4Q8Q0suNjNkGU=', + // Base64-encoded key used for decryption + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: 0, + ivLen: 16, + success: (data) => { + this.dealTxt = data.text; + }, + fail: (data, code) => { + prompt.showToast({ + message: (`### cipher.aes decrypt fail ### code = ${code}: ${data}`) + }) + }, + }); + } +} + +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md new file mode 100644 index 0000000000..310abffe57 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-configuration.md @@ -0,0 +1,45 @@ +# Application Configuration + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.i18n`](js-apis-i18n.md) and [`@ohos.intl`](js-apis-intl.md) instead. +> +> +> - 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. + + +## Modules to Import + + +``` +import configuration from '@system.configuration'; +``` + + +## configuration.getLocale + +getLocale(): <LocaleResponse> + +Obtains the current locale of the application, which is the same as the system locale. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Return values** +**Table 1** LocaleResponse + +| Name | Type | Description | +| -------- | -------- | -------- | +| language | string | Current language of the application, for example, **zh**. | +| countryOrRegion | string | Country or region, for example, **CN**. | +| dir | string | Text layout direction. Available values are as follows:
- **ltr**: The text direction is from left to right.
- **rtl**: The text direction is from right to left. | +| unicodeSetting5+ | string | Unicode key set determined by the locale.
For example, **{"nu":"arab"}** indicates that the current locale uses Arabic numerals.
If the current locale does not have a specific key set, an empty set is returned. | + +**Example** + +``` +export default { + getLocale() { + const localeInfo = configuration.getLocale(); + console.info(localeInfo.language); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md new file mode 100644 index 0000000000..c5b9283195 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -0,0 +1,75 @@ +# Device Information + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.deviceInfo`](js-apis-device-info.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import device from '@system.device'; +``` + + +## device.getInfo + +getInfo(Object): void + +Obtains the device information. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> Do not call **device.getInfo** before the **onShow** event of the home page. + +**System capability**: SystemCapability.Startup.SysInfo + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the device information is obtained | +| fail | Function | No | Called when the device information fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the device information is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| brand | string | Brand | +| manufacturer | string | Manufacturer | +| model | string | Model | +| product | string | Product number | +| language4+ | string | System language | +| region4+ | string | System region | +| windowWidth | number | Window width | +| windowHeight | number | Window height | +| screenDensity4+ | number | Screen density | +| screenShape4+ | string | Screen shape. The options are as follows:
- rect: rectangle screen
- circle: circle screen | +| apiVersion4+ | number | API version | +| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions. | +| deviceType4+ | string | Device type | + +The following error code will be returned if the device information fails to be obtained. + +| Error Code | Description | +| -------- | -------- | +| 200 | The returned result contains information that cannot be obtained. | + +**Example** + +``` +export default { + getInfo() { + device.getInfo({ + success: function(data) { + console.log('Device information obtained successfully. Device brand:' + data.brand); + }, + fail: function(data, code) { + console.log('Failed to obtain device information. Error code:'+ code + '; Error information: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-fetch.md b/en/application-dev/reference/apis/js-apis-system-fetch.md new file mode 100644 index 0000000000..e198f5562d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-fetch.md @@ -0,0 +1,105 @@ +# Data Request + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.net.http`](js-apis-http.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import fetch from '@system.fetch'; +``` + + +## fetch.fetch + +fetch(Object): void + +Obtains data through a network. + +**Required permissions:** ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | Resource URL. | +| data | string \| Object | No | Request parameter, which can be a string or a JSON object. For details, see Relationship between data and Content-Type. | +| header | Object | No | Request header. | +| method | string | No | Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**. | +| responseType | string | No | Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values of the success callback. | +| success | Function | No | Called when the network data is obtained successfully. | +| fail | Function | No | Called when the network data fails to be obtained. | +| complete | Function | No | Called when the execution is complete. | + + **Table1** Relationship between data and Content-Type + +| data | Content-Type | Description | +| -------- | -------- | -------- | +| string | Not set | The default value of Content-Type is text/plain, and the value of data is used as the request body. | +| string | Any type | The value of data is used as the request body. | +| Object | Not set | The default value of **Content-Type** is **application/x-www-form-urlencoded**. The **data** value is encoded based on the URL rule and appended in the request body. | +| Object | application/x-www-form-urlencoded | The value of data is encoded based on the URL rule and is used as the request body. | + +The following values will be returned when data is successfully obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| code | number | Server status code. | +| data | string \| Object | The type of the returned data is determined by **responseType**. For details, see Relationship between responseType and data returned by the success function. | +| headers | Object | All headers in the response from the server. | + + **Table2** Relationship between responseType and data returned by the success function + +| responseType | data | Description | +| -------- | -------- | -------- | +| N/A | string | When the type in the header returned by the server is **text/\***, **application/json**, **application/javascript**, or **application/xml**, the value is the text content. | +| text | string | Text content. | +| json | Object | A JSON object. | + +**Example** + +``` +export default { + data: { + responseData: 'NA', + url: "test_url", + }, + fetch: function () { + var that = this; + fetch.fetch({ + url: that.url, + success: function(response) { + console.info("fetch success"); + that.responseData = JSON.stringify(response); + }, + fail: function() { + console.info("fetch fail"); + } + }); + } +} +``` + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. +> +> ``` +> { +> "deviceConfig": { +> "default": { +> "network": { +> "cleartextTraffic": true +> } +> ... +> } +> } +> ... +> } +> ``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md new file mode 100644 index 0000000000..f05357dbe7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -0,0 +1,601 @@ +# File Storage + + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.fileio`](js-apis-fileio.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import file from '@system.file'; +``` + + +## file.move + +move(Object): void + +Moves a specified file to a given location. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| srcUri | string | Yes | URI of the file to move. | +| dstUri | string | Yes | URI of the location to which the file is to move. | +| success | Function | No | Called when the source file is moved to the specified location successfully. This function returns the URI of the destination location. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + move() { + file.move({ + srcUri: 'internal://app/myfiles1', + dstUri: 'internal://app/myfiles2', + success: function(uri) { + console.log('call success callback success'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.copy + +copy(Object): void + +Copies a file and saves the copy to a specified location. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| srcUri | string | Yes | URI of the file to copy. | +| dstUri | string | Yes | URI of the location to which the copy is to save.
The directory of application resources and URI of the **tmp** type are not supported. | +| success | Function | No | Called when the source file is copied and saved to the specified location successfully. This function returns the URI of the destination location. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + copy() { + file.copy({ + srcUri: 'internal://app/file.txt', + dstUri: 'internal://app/file_copy.txt', + success: function(uri) { + console.log('call success callback success'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.list + +list(Object): void + +Obtains the list of all files in a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | + +**Table1** FileInfo + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | File URI. | +| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | +| length | number | File size, in bytes. | +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + list() { + file.list({ + uri: 'internal://app/pic', + success: function(data) { + console.log(data.fileList); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.get + +get(Object): void + +Obtains information about a specified local file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | File URI. | +| recursive | boolean | No | Whether to recursively obtain the file list under a subdirectory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | File URI. | +| length | number | File size, in bytes. | +| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | +| type | string | File type. The values are as follows:
- **dir**: directory
- **file**: file | +| subFiles | Array | File list. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + get() { + file.get({ + uri: 'internal://app/file', + success: function(data) { + console.log(data.uri); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.delete + +delete(Object): void + +Deletes local files. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the file to delete, which cannot be an application resource path. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Incorrect parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + delete() { + file.delete({ + uri: 'internal://app/my_file', + success: function() { + console.log('call delete success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.writeText + +writeText(Object): void + +Writes text into a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | +| text | string | Yes | Character string to write into the local file. | +| encoding | string | No | Encoding format. The default format is UTF-8. | +| append | boolean | No | Whether to enable the append mode. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Incorrect parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + writeText() { + file.writeText({ + uri: 'internal://app/test.txt', + text: 'Text that just for test.', + success: function() { + console.log('call writeText success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.writeArrayBuffer + +writeArrayBuffer(Object): void + +Writes buffer data into a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | +| buffer | Uint8Array | Yes | Buffer from which the data is derived. | +| position | number | No | Offset to the position where the writing starts. The default value is **0**. | +| append | boolean | No | Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + writeArrayBuffer() { + file.writeArrayBuffer({ + uri: 'internal://app/test', + buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. + success: function() { + console.log('call writeArrayBuffer success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.readText + +readText(Object): void + +Reads text from a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. | +| encoding | string | No | Encoding format. The default format is UTF-8. | +| position | number | No | Position where the reading starts. The default value is the start position of the file. | +| length | number | No | Length of the text to be read (in bytes). The default value is **4096**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| text | string | Text read from the specified file. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | The file or directory does not exist. | +| 302 | The size of text to read exceeds 4096 bytes. | + +**Example** + +``` +export default { + readText() { + file.readText({ + uri: 'internal://app/text.txt', + success: function(data) { + console.log('call readText success: ' + data.text); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.readArrayBuffer + +readArrayBuffer(Object): void + +Reads buffer data from a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. | +| position | number | No | Position where the reading starts. The default value is the start position of the file. | +| length | number | No | Length of data to read. If this parameter is not set, the reading proceeds until the end of the file. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| buffer | Uint8Array | File content that is read | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + readArrayBuffer() { + file.readArrayBuffer({ + uri: 'internal://app/test', + position: 10, + length: 200, + success: function(data) { + console.log('call readArrayBuffer success: ' + data.buffer); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.access + +access(Object): void + +Checks whether a specified file or directory exists. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory or file. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + access() { + file.access({ + uri: 'internal://app/test', + success: function() { + console.log('call access success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.mkdir + +mkdir(Object): void + +Creates a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| recursive | boolean | No | Whether to recursively create upper-level directories of the specified directory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + mkdir() { + file.mkdir({ + uri: 'internal://app/test_directory', + success: function() { + console.log('call mkdir success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.rmdir + +rmdir(Object): void + +Deletes a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| recursive | boolean | No | Whether to recursively delete subfiles and subdirectories of the specified directory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + rmdir() { + file.rmdir({ + uri: 'internal://app/test_directory', + success: function() { + console.log('call rmdir success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md new file mode 100644 index 0000000000..ab53fb2d18 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -0,0 +1,211 @@ +# Geographic Location + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.geolocation`](js-apis-geolocation.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import geolocation from '@system.geolocation'; +``` + + +## Required Permissions + +ohos.permission.LOCATION + + +## geolocation.getLocation + +getLocation(Object): void + +Obtains the geographic location. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| timeout | number | No | Timeout duration, in milliseconds. The default value is **30000**.
The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.
The value is a 32-digit positive integer. If the value set is less than or equal to **0**, the default value will be used. | +| coordType | string | No | Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| longitude | number | Longitude | +| latitude | number | Latitude | +| altitude | number | Altitude | +| accuracy | number | Location accuracy | +| time | number | Time when the location is obtained | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 601 | Failed to obtain the required permission because the user rejected the request. | +| 602 | Permission not declared. | +| 800 | Operation times out due to a poor network condition or unavailable GPS. | +| 801 | System location disabled. | +| 802 | The method is called again while the previous execution result is not returned yet. | + +**Example** + +``` +export default { + getLocation() { + geolocation.getLocation({ + success: function(data) { + console.log('success get location data. latitude:' + data.latitude); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.getLocationType + +getLocationType(Object): void + +Obtains the supported location types. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| types | Array<string> | Available location types, ['gps', 'network'] | + +**Example** + +``` +export default { + getLocationType() { + geolocation.getLocationType({ + success: function(data) { + console.log('success get location type:' + data.types[0]); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.subscribe + +subscribe(Object): void + +Listens to the geographical location. If this method is called multiple times, the last call takes effect. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| coordType | string | No | Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**. | +| success | Function | Yes | Called when the geographical location changes | +| fail | Function | No | Called when the listening fails | + +The following values will be returned when the network type is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| longitude | number | Longitude | +| latitude | number | Latitude | +| altitude | number | Altitude | +| accuracy | number | Location accuracy | +| time | number | Time when the location is obtained | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 601 | Failed to obtain the required permission because the user rejected the request. | +| 602 | Permission not declared. | +| 801 | System location disabled. | + +**Example** + +``` +export default { + subscribe() { + geolocation.subscribe({ + success: function(data) { + console.log('get location. latitude:' + data.latitude); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.unsubscribe + +unsubscribe(): void + +Cancels listening to the geographical location. + +**System capability**: SystemCapability.Location.Location.Lite + +**Example** + +``` +export default { + unsubscribe() { + geolocation.unsubscribe(); + }, +} +``` + + +## geolocation.getSupportedCoordTypes + +getSupportedCoordTypes(): Array<string> + +Obtains coordinate system types supported by the device. + +**System capability**: SystemCapability.Location.Location.Lite + +**Return Value** + +| Type | Non-Null | Description | +| -------- | -------- | -------- | +| Array<string> | Yes | Coordinate system types, for example, **[wgs84, gcj02]**. | + +**Example** + +``` +export default { + getSupportedCoordTypes() { + var types = geolocation.getSupportedCoordTypes(); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md new file mode 100644 index 0000000000..f2057a8668 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -0,0 +1,125 @@ +# Media Query + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.mediaquery`](js-apis-mediaquery.md) instead. +> - 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. + + +## Modules to Import + + +``` +import mediaquery from '@system.mediaquery'; +``` + + +## mediaquery.matchMedia + +matchMedia(condition: string): MediaQueryList + +Creates a **MediaQueryList** object based on the query condition. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| condition | string | Yes | Query condition.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------------- | +| MediaQueryList | Attributes of the **MediaQueryList** object created. For details, see **MediaQueryList** attributes.| + +**Example** + +``` +export default { + matchMedia() { + var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); + }, +} +``` + +## MediaQueryEvent + +Defines a media query event. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ----- | +| matches | boolean | Yes | Matching result.| + +## MediaQueryList + +Defines a media query list. + +### Attributes + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ----------------- | +| media | string | No | Serialized media query condition. This parameter is read-only.| +| matches | boolean | Yes | Matching result. | + +### onchange + +onchange?: (matches: boolean) => void + +Called when the **matches** value changes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | -------------- | +| matches | boolean | Yes | New **matches** value.| + + +### MediaQueryList.addListener + +addListener(callback: (event: MediaQueryEvent) => void): void + +Adds a listener for this **MediaQueryList** object. The listener must be added before **onShow** is called, that is, it must be added in the **onInit** or **onReady** API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | -------------- | +| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the matching condition changes.| + +**Example** + +``` +mMediaQueryList.addListener(maxWidthMatch); +``` + + +### MediaQueryList.removeListener + +removeListener(callback: (event: MediaQueryEvent) => void): void + +Removes the listener for this **MediaQueryList** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------- | ---- | -------------- | +| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the matching condition changes.| + +**Example** + +``` +mMediaQueryList.removeListener(maxWidthMatch); +``` diff --git a/en/application-dev/reference/apis/js-apis-system-network.md b/en/application-dev/reference/apis/js-apis-system-network.md new file mode 100644 index 0000000000..1bf1218898 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -0,0 +1,134 @@ +# Network State + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import network from '@system.network'; +``` + + +## Required Permissions + +ohos.permission.GET_WIFI_INFO + +ohos.permission.GET_NETWORK_INFO + + +## network.getType + +getType(Object): void + +Obtains the network type. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the multimedia volume is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| metered | boolean | Whether the billing is based on the data volume. | +| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 602 | The current permission is not declared. | + +**Example** + +``` +export default { + getType() { + network.getType({ + success: function(data) { + console.log('success get network type:' + data.type); + }, + fail: function(data, code) { + console.log('fail to get network type code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## network.subscribe + +subscribe(Object): void + +Listens to the network connection state. If this method is called multiple times, the last call takes effect. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the network connection state changes | +| fail | Function | No | Called when the multimedia volume fails to be obtained. | + +The following value will be returned when the multimedia volume is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| metered | boolean | Whether the billing is based on the data volume. | +| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | + +One of the following error codes will be returned if the listening fails. + +| Error Code | Description | +| -------- | -------- | +| 602 | The current permission is not declared. | +| 200 | The subscription fails. | + +**Example** + +``` +export default { + subscribe() { + network.subscribe({ + success: function(data) { + console.log('network type change type:' + data.type); + }, + fail: function(data, code) { + console.log('fail to subscribe network, code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## network.unsubscribe + +unsubscribe(): void + +Cancels listening to the network connection state. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Example** + +``` +export default { + unsubscribe() { + network.unsubscribe(); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md new file mode 100644 index 0000000000..c6453ec28f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -0,0 +1,60 @@ +# Application Management + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.bundle`](js-apis-Bundle.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import pkg from '@system.package'; +``` + + +## package.hasInstalled + +hasInstalled(Object): void + +Checks whether an application exists, or whether a native application has been installed. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**Parameter** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes | Application bundle name | +| success | Function | No | Called when the check result is obtained | +| fail | Function | No | Called when the check result fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the check result is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| result | boolean | Whether the application exists, or whether the native application has been installed | + +**Example** + +``` +export default { + hasInstalled() { + pkg.hasInstalled({ + bundleName: 'com.example.bundlename', + success: function(data) { + console.log('package has installed: ' + data); + }, + fail: function(data, code) { + console.log('query package fail, code: ' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md new file mode 100644 index 0000000000..f894715391 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -0,0 +1,188 @@ +# Prompt + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 8. You are advised to use ['@ohos.prompt](js-apis-prompt.md)' instead. +> +> +> - 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. + + +## Modules to Import + + +``` +import prompt from '@system.prompt'; +``` + +## prompt.showToast + +showToast(options: ShowToastOptions): void + +Shows the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | --------------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Options for showing the toast.| + +**Example** + +``` +export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } +} +``` + + +## prompt.showDialog + +showDialog(options: ShowDialogOptions): void + +Shows the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ----------- | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Options for showing the dialog box.| + + +**Example** + +``` +export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button', + color: '#666666', + }, + ], + success: function(data) { + console.log('dialog success callback, click button : ' + data.index); + }, + cancel: function() { + console.log('dialog cancel callback'); + }, + }); + } +} +``` + +## prompt.showActionMenu6+ + +showActionMenu(options: ShowActionMenuOptions): void + +Shows the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| options | [ShowActionMenuOptions](#showactionmenuoptions) | Yes | Options for showing the action menu.| + + +**Example** + +``` +export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ], + success: function(data) { + console.log('dialog success callback, click button : ' + data.tapIndex); + }, + fail: function(data) { + console.log('dialog fail callback' + data.errMsg); + }, + }); + } +} +``` +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------------------- | -------------- | ---- | ---------------------------------------- | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom5+ | string\|number | No | Distance between the toast frame and the bottom of the screen. This parameter is available only on phones and tablets. | + +## Button + +Defines the prompt information of a button. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------- | +| text | string | Yes | Text displayed on the button.| +| color | string | Yes | Color of the button.| + +## ShowDialogSuccessResponse + +Defines the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------- | +| index | number | Yes | Data index.| + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| message | string | No | Text body. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| +| success | (data: [ShowDialogSuccessResponse](#showdialogsuccessresponse)) => void | No | Callback upon success. | +| cancel | (data: string, code: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Called when the API call is complete. | + +## ShowActionMenuOptions6+ + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?] | Yes | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported.| +| success | (tapIndex: number, errMsg: string) => void | No | Invoked when a dialog box is displayed. | +| fail | (errMsg: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Invoked when a dialog box is closed. | diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md new file mode 100644 index 0000000000..53fa3bf822 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -0,0 +1,189 @@ +# Uploading and Downloading + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.request`](js-apis-request.md) instead. +> +> - The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import request from '@system.request'; +``` + +## Required Permissions + +ohos.permission.INTERNET. + + +## request.upload + +upload(Object): void + +Uploads files. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | URL of the upload server. | +| header | Object | No | Request header. | +| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| files | Array<File> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | +| data | Array<RequestData> | No | Form data in the request body. | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +**Table 1** File + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| filename | string | No | File name in the header when **multipart** is used. | +| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | +| uri | string | Yes | Local storage path of a file. | +| type | string | No | Type of the file content. By default, the type is obtained based on the suffix of the file name or URI. | + +**Table 2** RequestData + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| name | string | Yes | Name of the form element | +| value | string | Yes | Value of the form element | + +The following values will be returned when the files are successfully uploaded. + +| Name | Type | Description | +| -------- | -------- | -------- | +| code | number | HTTP status code returned by the server. | +| data | string | Content returned by the server. The value type is determined by the type in the returned headers. | +| headers | Object | Headers returned by the server. | + +**Example** + +``` +export default { + upLoad() { + request.upload({ + url: 'http://www.path.com', + files: [ + { + uri: 'internal://cache/path/to/file.txt', + name: 'file', + filename: 'file.txt', + }, + ], + data:[ + { + name: 'name1', + value: 'value', + }, + ], + success: function(data) { + console.log('upload success, code:' + data.code); + }, + fail: function() { + console.log('upload fail'); + }, + }); + } +} +``` + + +## request.download + +download(Object): void + +Downloads files. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | Resource URL. | +| header | Object | No | Request header. | +| description | string | No | Download description. The default value is the file name. | +| filename | string | No | Name of the file to download. The value is obtained from the current request or resource URL by default. | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| token | string | Download token, which is used to obtain the download status. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 400 | Download task failed | + +**Example** + +``` +export default { + downLoad() { + request.download({ + url: 'http://www.path.com', + success: function(data) { + console.log('call success callback success: ' + data.token); + }, + fail: function(data, code) { + console.log('handling fail'); + }, + }); + } +} +``` + + +## request.onDownloadComplete + +onDownloadComplete(Object): void + +Listens to download task status. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| token | string | Yes | Token of the result returned by the download method | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | URI of the download file | + +One of the following error codes will be returned if the listening fails. + +| Error Code | Description | +| -------- | -------- | +| 400 | Download task failed | +| 401 | Download task not exist | + +**Example** + +``` +export default { + onDownloadComplete() { + request.onDownloadComplete({ + token: 'token-index', + success: function(data) { + console.log('download success, uri:' + data.uri); + }, + fail: function(data, code) { + console.log('download fail'); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md new file mode 100644 index 0000000000..c69a1599f6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -0,0 +1,398 @@ +# Page Routing + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.router`](js-apis-router.md) instead. +> +> +> - 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. + + +## Modules to Import + + +``` +import router from '@system.router'; +``` + +## router.push + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | -------------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. For details, see **RouterOptions**.| + +**Example** + +``` +// Current page +export default { + pushPage() { + router.push({ + uri: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } +} +``` + + +``` +// routerpage2 page +export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The page routing stack supports a maximum of 32 pages. + + +## router.replace + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | -------------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. For details, see **RouterOptions**.| + +**Example** + +``` +// Current page +export default { + replacePage() { + router.replace({ + uri: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } +} +``` + + +``` +// detail page +export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } +} +``` + +## router.back + +back(options?: BackRouterOptions): void + +Returns to the previous page or a specified page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ----------------------- | +| options | [BackRouterOptions](#backrouteroptions) | Yes | For details, see **BackRouterOptions**.| + +**Example** + +``` +// index page +export default { + indexPushPage() { + router.push({ + uri: 'pages/detail/detail', + }); + } +} +``` + + +``` +// detail page +export default { + detailPushPage() { + router.push({ + uri: 'pages/mall/mall', + }); + } +} +``` + + +``` +// Navigate from the mall page to the detail page through router.back(). +export default { + mallBackPage() { + router.back(); + } +} +``` + + +``` +// Navigate from the detail page to the index page through router.back(). +export default { + defaultBack() { + router.back(); + } +} +``` + + +``` +// Return to the detail page through router.back(). +export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. + +## router.getParams + +getParams(): ParamsInterface + +Obtains parameter information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------- | +| [ParamsInterface](#paramsinterface) | For details, see **ParamsInterface**.| + +## router.clear + +clear(): void + +Clears all historical pages in the stack and retains only the current page at the top of the stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + +``` +export default { + clearPage() { + router.clear(); + } +} +``` + +## router.getLength + +getLength(): string + +Obtains the number of pages in the current stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Number of pages in the stack. The maximum value is **32**.| + +**Example** + +``` +export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } +} +``` + +## router.getState + +getState(): RouterState + +Obtains state information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------- | ----------------- | +| [RouterState](#routerstate) | For details, see **RouterState**.| + +**Example** + +``` +export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } +} +``` + +## router.enableAlertBeforeBackPage6+ + +enableAlertBeforeBackPage(options: EnableAlertBeforeBackPageOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | -------------------------------------- | +| options | [EnableAlertBeforeBackPageOptions](#enableAlertbeforebackpageoptions6) | Yes | For details, see **EnableAlertBeforeBackPageOptions**.| + +**Example** + +``` +export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } +} +``` + +## router.disableAlertBeforeBackPage6+ + +disableAlertBeforeBackPage(options?: DisableAlertBeforeBackPageOptions): void + +Disables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------------------------------------- | +| options | [DisableAlertBeforeBackPageOptions](#disablealertbeforebackpageoptions6) | No | For details, see **DisableAlertBeforeBackPageOptions**.| + +**Example** + +``` +export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage({ + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } +} +``` + +## RouterOptions + +Defines the page routing parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| uri | string | Yes | URI of the destination page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
-pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| + + +## BackRouterOptions + +Defines the parameters for routing back. + +**System capability**: The items in the table below require different system capabilities. For details, see the table. + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| params | Object | No | Data that needs to be passed to the destination page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| + +## RouterState + +Defines the page state. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------- | +| index | number | Yes | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.| +| name | string | Yes | Name of the current page, that is, the file name. | +| path | string | Yes | Path of the current page. | + +## EnableAlertBeforeBackPageOptions6+ + +Defines the **EnableAlertBeforeBackPage** parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ------------------------ | ---- | ------------------------- | +| message | string | Yes | Content displayed in the confirm dialog box. | +| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. | +| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.| +| complete | () => void | No | Called when the API call is complete. | + +## DisableAlertBeforeBackPageOptions6+ + +Define the **DisableAlertBeforeBackPage** parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ------------------------ | ---- | ------------------------- | +| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. | +| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.| +| complete | () => void | No | Called when the API call is complete. | + +## ParamsInterface + +| Name | Type | Description | +| ------------- | ------ | ------- | +| [key: string] | Object | List of routing parameters.| diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md new file mode 100644 index 0000000000..2440183d41 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -0,0 +1,162 @@ +# Data Storage + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.data.storage`](js-apis-data-storage.md) instead. +> +> - 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. + + +## Modules to Import + + +``` +import storage from '@system.storage'; +``` + + +## storage.get + +get(Object): void + +Reads the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Content index. | +| default | string | No | Default value returned when the **key** does not exist. | +| success | Function | No | Called when the stored content is successfully read. | +| fail | Function | No | Called when the stored content fails to be read. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageGet() { + storage.get({ + key: 'storage_key', + success: function(data) { + console.log('call storage.get success: ' + data); + }, + fail: function(data, code) { + console.log('call storage.get fail, code: ' + code + ', data: ' + data); + }, + complete: function() { + console.log('call complete'); + }, + }); + } +} +``` + + +## storage.set + +set(Object): void + +Modifies the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Index of the stored content to be modified. | +| value | string | No | Target storage content. The maximum number of characters allowed is 128. | +| success | Function | No | Called when the stored content is modified successfully. | +| fail | Function | No | Called when the stored content fails to be modified. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageSet() { + storage.set({ + key: 'storage_key', + value: 'storage value', + success: function() { + console.log('call storage.set success.'); + }, + fail: function(data, code) { + console.log('call storage.set fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## storage.clear + +clear(Object): void + +Clears the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the stored content is cleared successfully | +| fail | Function | No | Called when the stored content fails to be cleared | +| complete | Function | No | Called when the execution is complete | + +**Example** + +``` +export default { + storageClear() { + storage.clear({ + success: function() { + console.log('call storage.clear success.'); + }, + fail: function(data, code) { + console.log('call storage.clear fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## storage.delete + +delete(Object): void + +Deletes the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Content index. | +| success | Function | No | Called when the stored content is deleted successfully. | +| fail | Function | No | Called when the stored content fails to be deleted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageDelete() { + storage.delete({ + key: 'Storage1', + success: function() { + console.log('call storage.delete success.'); + }, + fail: function(data, code) { + console.log('call storage.delete fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 31f3f13036..35096fe9a7 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -20,7 +20,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -51,7 +51,7 @@ Sets the system time. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -82,7 +82,7 @@ getCurrentTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -109,7 +109,7 @@ getCurrentTime(isNano?: boolean): Promise<number> Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -138,7 +138,7 @@ getRealActiveTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, excluding the deep sleep time. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -165,7 +165,7 @@ getRealActiveTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, excluding the deep sleep time. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -194,7 +194,7 @@ getRealTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -221,7 +221,7 @@ getRealTime(): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -252,7 +252,7 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -282,7 +282,7 @@ Sets the system date. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -312,7 +312,7 @@ getDate(callback: AsyncCallback<Date>): void Obtains the current system date. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -338,7 +338,7 @@ getDate(): Promise<Date> Obtains the current system date. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - Return value | Type| Description| @@ -364,7 +364,7 @@ Sets the system time zone. This API uses an asynchronous callback to return the **Required permissions**: ohos.permission.SET_TIME_ZONE -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -393,7 +393,7 @@ Sets the system time zone. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME_ZONE -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -422,7 +422,7 @@ getTimezone(callback: AsyncCallback<string>): void Obtains the system time zone. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -448,7 +448,7 @@ getTimezone(): Promise<string> Obtains the system time zone. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - Return value | Type| Description| diff --git a/en/application-dev/reference/apis/js-apis-testRunner.md b/en/application-dev/reference/apis/js-apis-testRunner.md new file mode 100644 index 0000000000..47f1dc8dad --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-testRunner.md @@ -0,0 +1,51 @@ +# TestRunner + +> **Note** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import TestRunner from '@ohos.application.testRunner' +``` + + + +## TestRunner.onPrepare + +onPrepare(): void + +Prepares the unit test environment to run test cases. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + +```js +export default class UserTestRunner extends TestRunner { + onPrepare() { + console.log("Trigger onPrepare") + } +}; +``` + + + +## TestRunner.onRun + +onRun(): void + +Runs test cases. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + +```js +export default class UserTestRunner extends TestRunner { + onRun() { + console.log("Trigger onRun") + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index 047a66fbf4..8aa15caf96 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -45,7 +45,7 @@ let treeMap = new TreeMap(); ### isEmpty -isEmpty(): boolean; +isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -65,7 +65,7 @@ let result = treeMap.isEmpty(); ### hasKey -hasKey(key: K): boolean; +hasKey(key: K): boolean Checks whether this container has the specified key. @@ -73,7 +73,7 @@ Checks whether this container has the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to query.| +| key | K | Yes| Key to check.| **Return value** @@ -101,7 +101,7 @@ Checks whether this container has the specified value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value to query.| +| value | V | Yes| Value to check.| **Return value** @@ -149,7 +149,7 @@ let result = treeMap.get("sdfs"); ### getFirstKey -getFirstKey(): K; +getFirstKey(): K Obtains the first key in this container. @@ -171,7 +171,7 @@ let result = treeMap.getFirstKey(); ### getLastKey -getLastKey(): K; +getLastKey(): K Obtains the last key in this container. @@ -215,6 +215,7 @@ treeMap.setAll(map); ### set + set(key: K, value: V): Object Adds an entry to this container. @@ -242,7 +243,7 @@ treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); ### remove -remove(key: K): V; +remove(key: K): V Removes the entry with the specified key from this container. @@ -326,6 +327,7 @@ let result = treeMap.getHigherKey("sdfs"); ``` ### replace + replace(key: K, newValue: V): boolean Replaces an entry in this container. @@ -424,7 +426,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void +forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -438,8 +440,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | TreeMap | No| Instance that invokes the **forEach** method.| **Example** @@ -484,7 +486,7 @@ while(temp != undefined) { ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<[K, V]>; +[Symbol.iterator]\(): IterableIterator<[K, V]> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index bc937047ab..a37b5515c9 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -136,6 +136,7 @@ let result = treeSet.getLastValue(); ### add + add(value: T): boolean Adds an entry to this container. @@ -162,7 +163,7 @@ let result = treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); ### remove -remove(value: T): boolean; +remove(value: T): boolean Removes the entry with the specified key from this container. @@ -335,7 +336,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void +forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -349,7 +350,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key | T | No| Key of the entry that is currently traversed (same as **value**).| | set | TreeSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md new file mode 100644 index 0000000000..b554e47f48 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -0,0 +1,1058 @@ +# UiTest + +>**NOTE** +> +>The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import {UiDriver,BY,MatchPattern} from '@ohos.uitest' +``` + +## By + +The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. +The API capabilities provided by the **By** class exhibit the following features: + +- Allows one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. + +- Provides multiple match patterns for component attributes. + +- Supports absolute positioning and relative positioning for components. APIs such as **isBefore** and **isAfter** can be used to specify the features of adjacent components to assist positioning. + +All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode, for example, **BY.text('123').type('button')**. + +### enum MatchPattern + +Enumerates the match patterns supported for component attributes. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | Contain the given value. | +| STARTS_WITH | 2 | Start with the given value.| +| ENDS_WITH | 3 | End with the given value.| + +### By.text + +text(txt:string,pattern?:MatchPattern):By + +Specifies the text attribute of the target component. Multiple match patterns are supported. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------ | ---- | ---------------------------------- | +| txt | string | Yes | Component text, used to match the target component.| +| pattern | MatchPattern | No | Match pattern. The default value is **EQUALS**. | + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute + of the target component. +``` + + +### By.key + +key(key:string):By; + +Specifies the key attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------- | +| key | string | Yes | Component key.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute + of the target component. +``` + + +### By.id + +id(id:number):By; + +Specifies the ID property of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| id | number | Yes | Component ID.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.id(123) // Use the static constructor BY to create a By object and specify the ID attribute + of the target component. +``` + + +### By.type + +type(tp:string):By; + +Specifies the type property of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| tp | string | Yes | Component type.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute + of the target component. +``` + + +### By.clickable + +clickable(b?:bool):By; + +Specifies the clickable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Clickable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable attribute + of the target component. +``` + + +### By.scrollable + +scrollable(b?:bool):By; + +Specifies the scrollable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | +| b | bool | No | Scrollable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable attribute + of the target component. +``` + +### By.enabled + +enabled(b?:bool):By; + +Specifies the enable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| b | bool | No | Enable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enable attribute + of the target component. +``` + +### By.focused + +focused(b?:bool):By; + +Specifies the focused attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------ | +| b | bool | No | Focused status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the focused attribute + of the target component. +``` + +### By.selected + +selected(b?:bool):By; + +Specifies the selected attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Selected status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected attribute + of the target component. +``` + +### By.isBefore + +isBefore(by:By):By; + +Specifies the attributes of the component before which the target component is located. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| by | By | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes + of the component before which the target component is located. +``` + +### By.isAfter + +isAfter(by:By):By; + +Specifies the attributes of the component after which the target component is located. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| by | By | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes + of the component after which the target component is located. +``` + +## UiComponent + +In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. +All APIs provided by this class use a promise to return the result and must be invoked using **await**. + +### UiComponent.click + +click():Promise; + +Clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.click() +} +``` + +### UiComponent.doubleClick + +doubleClick():Promise; + +Double-clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await buttont.doubleClick() +} +``` + +### UiComponent.longClick + +longClick():Promise; + +Long-clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.longClick() +} +``` + +### UiComponent.getId + +getId():Promise; + +Obtains the ID of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise; | Promise used to return the component ID.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let num = await button.getId() +} +``` + +### UiComponent.getKey + +getKey():Promise; + +Obtains the key of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | -------------------------- | +| Promise; | Promise used to return the component key.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let str_key = await button.getKey() +} +``` + +### UiComponent.getText + +getText():Promise; + +Obtains the text information of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------- | +| Promise; | Promise used to return the text information of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let text = await button.getText() +} +``` + +### UiComponent.getType + +getType():Promise; + +Obtains the type of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------- | +| Promise; | Promise used to return the component type.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let type = await button.getType() +} +``` + +### UiComponent.isClickable + +isClickable():Promise; + +Obtains the clickable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the clickable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isClickable()) { + console.info('This button can be Clicked') + } + else{ + console.info('This button can not be Clicked') + } +} +``` + +### UiComponent.isScrollable + +isScrollable():Promise; + +Obtains the scrollable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the scrollable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.scrollable(true)) + if(await scrollBar.isScrollable()) { + console.info('This scrollBar can be operated') + } + else{ + console.info('This scrollBar can not be operated') + } +} +``` + + +### UiComponent.isEnabled + +isEnabled():Promise; + +Obtains the enable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise; | Promise used to return the enable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isEnabled()) { + console.info('This button can be operated') + } + else{ + console.info('This button can not be operated') + } +} + +``` + +### UiComponent.isFocused + +isFocused():Promise; + +Obtains the focused status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | --------------------------------- | +| Promise; | Promise used to return the focused status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isFocused()) { + console.info('This button is focused') + } + else{ + console.info('This button is not focused') + } +} +``` + +### UiComponent.isSelected + +isSelected():Promise; + +Obtains the selected status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the selected status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isSelected()) { + console.info('This button is selected') + } + else{ + console.info('This button is not selected') + } +} +``` + +### UiComponent.inputText + +inputText(text: string):Promise; + +Enters text into this component (available for text boxes). + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------- | +| text | string | Yes | Text to be entered to the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.inputText('next page') +} +``` + +### UiComponent.scrollSearch + +scrollSearch(by:By):Promise; + +Scrolls on this component to search for the target component (available for lists). + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise; | Promise used to return the target component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.scrollable(true)) + let button = await scrollBar.scrollSearch(BY.text('next page')) +} +``` + +## UiDriver + +The **UiDriver** class is the main entry to the **uitest** test framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. +All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. + +### UiDriver.create + +static create():UiDriver; + +Creates a **UiDriver** object and returns the object created. This API is a static API. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ------- | ---------------------- | +| UiDrive | Returns the **UiDriver** object created.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() +} +``` + +### UiDriver.delayMs + +delayMs(duration:number):Promise; + +Delays this **UiDriver** object within the specified duration. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| duration | number | Yes | Duration of time.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.delayMs(1000) +} +``` + +### UiDriver.findComponent + +findComponent(by:By):Promise; + +Searches this **UiDriver** object for the target component that has the given attributes. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise; | Promise used to return the found component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.text('next page')) +} +``` + +### UiDriver.findComponents + +findComponents(by:By):Promise>; + +Searches this **UiDriver** object for all components that match the given attributes. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| ---------------------------- | ------------------------------------- | +| Promise>; | Promise used to return a list of found components.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let buttonList = await driver.findComponents(BY.text('next page')) +} +``` + +### UiDriver.assertComponentExist + +assertComponentExist(by:By):Promise; + +Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.assertComponentExist(BY.text('next page')) +} +``` + +### UiDriver.pressBack + +pressBack():Promise; + +Presses the Back button on this **UiDriver** object. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.pressBack() +} +``` + +### UiDriver.triggerKey + +triggerKey(keyCode:number):Promise; + +Triggers the key of this **UiDriver** object that matches the given key code. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------- | +| keyCode | number | Yes | Key code.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.triggerKey(123) +} +``` + +### UiDriver.click + +click(x:number,y:number):Promise; + +Clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.click(100,100) +} +``` + +### UiDriver.doubleClick + +doubleClick(x:number,y:number):Promise; + +Double-clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.doubleClick(100,100) +} +``` + +### UiDriver.longClick + +longClick(x:number,y:number):Promise; + +Long-clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.longClick(100,100) +} +``` + +### UiDriver.swipe + +swipe(startx:number,starty:number,endx:number,endy:number):Promise; + +Swipes from the start point to the end point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | ------------------------------------------- | +| startx,starty | number,number | Yes | Coordinate information of the start point in the (number,number) format.| +| endx,endy | number,number | Yes | Coordinate information of the end point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.swipe(100,100,200,200) +} +``` + +### UiDriver.screenCap + +screenCap(savePath:string):Promise; + +Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | +| savePath | string | Yes | File save path.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.screenCap('/local/tmp/') +} +``` diff --git a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md b/en/application-dev/reference/apis/js-apis-uripermissionmanager.md deleted file mode 100644 index b004a0a4c9..0000000000 --- a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md +++ /dev/null @@ -1,78 +0,0 @@ -# UriPermissionManager - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements URI permission management. - - -## Modules to Import - - -``` -import UriPermissionManager from '@@ohos.application.UriPermissionManager'; -``` - - -## verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback<number>): void - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a callback to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - | callback | AsyncCallback<number> | Yes| Callback used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -- Example - - ``` - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId, (result) => { - console.log("result.code = " + result.code) - }) // accessTokenId is obtained through the **BundleManager** API. - ``` - - -## verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise<number> - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a promise to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -- Example - - ``` - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId) - .then((data) => { - console.log('Verification succeeded.' + data) - }).catch((error) => { - console.log('Verification failed.'); - }) - ``` diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 51a5615b69..7ff865803c 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -419,122 +419,139 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface). +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| address | number | Endpoint address.
**System capability**: SystemCapability.USB.USBManager| -| attributes | number | Endpoint attributes.
**System capability**: SystemCapability.USB.USBManager| -| interval | number | Endpoint interval.
**System capability**: SystemCapability.USB.USBManager| -| maxPacketSize | number | Maximum size of data packets on the endpoint.
**System capability**: SystemCapability.USB.USBManager| -| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction.
**System capability**: SystemCapability.USB.USBManager| -| number | number | Endpoint number.
**System capability**: SystemCapability.USB.USBManager| -| type | number | Endpoint type.
**System capability**: SystemCapability.USB.USBManager| -| interfaceId | number | Unique ID of the interface to which the endpoint belongs.
**System capability**: SystemCapability.USB.USBManager| +| address | number | Endpoint address.| +| attributes | number | Endpoint attributes.| +| interval | number | Endpoint interval.| +| maxPacketSize | number | Maximum size of data packets on the endpoint.| +| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction.| +| number | number | Endpoint number.| +| type | number | Endpoint type.| +| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| ## USBInterface Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **USBInterface** instances, each providing a specific function. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| id | number | Unique ID of the USB interface.
**System capability**: SystemCapability.USB.USBManager| -| protocol | number | Interface protocol.
**System capability**: SystemCapability.USB.USBManager| -| clazz | number | Device type.
**System capability**: SystemCapability.USB.USBManager| -| subClass | number | Device subclass.
**System capability**: SystemCapability.USB.USBManager| -| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Interface name.
**System capability**: SystemCapability.USB.USBManager| -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface.
**System capability**: SystemCapability.USB.USBManager| +| id | number | Unique ID of the USB interface.| +| protocol | number | Interface protocol.| +| clazz | number | Device type.| +| subClass | number | Device subclass.| +| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| +| name | string | Interface name.| +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface.| ## USBConfig Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| id | number | Unique ID of the USB configuration.
**System capability**: SystemCapability.USB.USBManager| -| attributes | number | Configuration attributes.
**System capability**: SystemCapability.USB.USBManager| -| maxPower | number | Maximum power consumption, in mA.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Configuration name, which can be left empty.
**System capability**: SystemCapability.USB.USBManager| -| isRemoteWakeup | boolean | Support for remote wakeup.
**System capability**: SystemCapability.USB.USBManager| -| isSelfPowered | boolean | Support for independent power supplies.
**System capability**: SystemCapability.USB.USBManager| -| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes.
**System capability**: SystemCapability.USB.USBManager| +| id | number | Unique ID of the USB configuration.| +| attributes | number | Configuration attributes.| +| maxPower | number | Maximum power consumption, in mA.| +| name | string | Configuration name, which can be left empty.| +| isRemoteWakeup | boolean | Support for remote wakeup.| +| isSelfPowered | boolean | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes.| ## USBDevice -Represents the USB device information. +Represents USB device information. + +**System capability**: SystemCapability.USB.USBManager | Name| Type| Description| | -------- | -------- | -------- | -| busNum | number | Bus address.
**System capability**: SystemCapability.USB.USBManager| -| devAddress | number | Device address.
**System capability**: SystemCapability.USB.USBManager| -| serial | string | Device SN.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Device name.
**System capability**: SystemCapability.USB.USBManager| -| manufacturerName | string | Device manufacturer.
**System capability**: SystemCapability.USB.USBManager| -| productName | string | Product information.
**System capability**: SystemCapability.USB.USBManager| -| version | string | Version.
**System capability**: SystemCapability.USB.USBManager| -| vendorId | number | Vendor ID.
**System capability**: SystemCapability.USB.USBManager| -| productId | number | Product ID.
**System capability**: SystemCapability.USB.USBManager| -| clazz | number | Device class.
**System capability**: SystemCapability.USB.USBManager| -| subClass | number | Device subclass.
**System capability**: SystemCapability.USB.USBManager| -| protocol | number | Device protocol code.
**System capability**: SystemCapability.USB.USBManager| -| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.
**System capability**: SystemCapability.USB.USBManager| +| busNum | number | Bus address.| +| devAddress | number | Device address.| +| serial | string | Device SN.| +| name | string | Device name.| +| manufacturerName | string | Device manufacturer.| +| productName | string | Product information.| +| version | string | Version.| +| vendorId | number | Vendor ID.| +| productId | number | Product ID.| +| clazz | number | Device class.| +| subClass | number | Device subclass.| +| protocol | number | Device protocol code.| +| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.| ## USBDevicePipe Represents a USB device pipe, which is used to determine a USB device. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| busNum | number | Bus address.
**System capability**: SystemCapability.USB.USBManager| -| devAddress | number | Device address.
**System capability**: SystemCapability.USB.USBManager| +| busNum | number | Bus address.| +| devAddress | number | Device address.| ## USBControlParams Represents control transfer parameters. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | | request | number | Request type.| -| target | [USBRequestTargetType](#usbrequesttargettype) | Represents the request target type.
**System capability**: SystemCapability.USB.USBManager| -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Request control type.
**System capability**: SystemCapability.USB.USBManager| -| value | number | Request parameters
**System capability**: SystemCapability.USB.USBManager| -| index | number | Index of the request parameter value.
**System capability**: SystemCapability.USB.USBManager| -| data | Uint8Array | Buffer for writing or reading data.
**System capability**: SystemCapability.USB.USBManager| +| target | [USBRequestTargetType](#usbrequesttargettype) | Represents the request target type.| +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Request control type.| +| value | number | Request parameters| +| index | number | Index of the request parameter value.| +| data | Uint8Array | Buffer for writing or reading data.| ## USBRequestTargetType Represents the request target type. +**System capability**: SystemCapability.USB.USBManager | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_TARGET_DEVICE | 0 | Device.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_OTHER | 3 | Others
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_TARGET_DEVICE | 0 | Device.| +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.| +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| +| USB_REQUEST_TARGET_OTHER | 3 | Others| ## USBControlRequestType Enumerates control request types. +**System capability**: SystemCapability.USB.USBManager + | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_TYPE_STANDARD | 0 | Standard
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TYPE_CLASS | 1 | Class.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TYPE_VENDOR | 2 | Vendor
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_TYPE_STANDARD | 0 | Standard| +| USB_REQUEST_TYPE_CLASS | 1 | Class.| +| USB_REQUEST_TYPE_VENDOR | 2 | Vendor| ## USBRequestDirection Enumerates request directions. +**System capability**: SystemCapability.USB.USBManager + | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| +| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index 1ce2456d56..02992c0a5f 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,66 +1,102 @@ -# User Authentication +# User Authentication ->**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. +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import +## Modules to Import -``` +```js import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## System Capabilities - -SystemCapability.UserIAM.UserAuth - -## Required Permissions - -ohos.permission.ACCESS\_BIOMETRIC - -## Sample Code +## Example -``` +```js +// API version 6 import userIAM_userAuth from '@ohos.userIAM.userAuth'; export default { startAuth() { console.info("start auth"); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - // Add the logic for displaying the prompt message. - }; let auth = userIAM_userAuth.getAuthenticator(); - auth.on("tip", tipCallback); auth.execute("FACE_ONLY", "S2").then((code)=>{ - auth.off("tip", tipCallback); console.info("auth success"); - // Add the logic for authentication success. + // Add the logic to be executed when the authentication is successful. }).catch((code)=>{ - auth.off("tip", tipCallback); console.error("auth fail, code = " + code); - // Add the logic for authentication failure. + // Add the logic to be executed when the authentication fails. + }); + } +} +``` + +```js +// API version 8 +import userIAM_userAuth from '@ohos.userIAM.userAuth'; +let auth = new userIAM_userAuth.UserAuth(); + +export default { + getVersion() { + console.info("start get version"); + let version = this.auth.getVersion(); + console.info("auth version = " + version); + }, + + startAuth() { + console.info("start auth"); + this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == 'SUCCESS') { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } }); }, checkAuthSupport() { console.info("start check auth support"); - let auth = userIAM_userAuth.getAuthenticator(); - let checkCode = auth.checkAvailability("FACE_ONLY", "S2"); - if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) { + let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("check auth support success"); - // Add the logic for the specified authentication type supported. + // Add the logic to be executed if the specified authentication type is supported. } else { console.error("check auth support fail, code = " + checkCode); - // Add the logic for the authentication type that is not supported. + // Add the logic to be executed if the specified authentication type is not supported. } }, cancelAuth() { console.info("start cancel auth"); - let auth = userIAM_userAuth.getAuthenticator(); - let cancelCode = auth.cancel(); + // Obtain contextId using auth(). + let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + console.info("auth onResult result = " + result); + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + console.info("auth onAcquireInfo module = " + module); + } + }); + let cancelCode = this.auth.cancel(contextId); if (cancelCode == userIAM_userAuth.Result.SUCCESS) { console.info("cancel auth success"); } else { @@ -70,800 +106,504 @@ export default { } ``` -## userIAM\_userAuth.getAuthenticator - -getAuthenticator\(\): Authenticator - -Obtains an **Authenticator** object for user authentication. 6+ - -Obtains an **Authenticator** object to check the device's capability of user authentication, perform or cancel user authentication, and obtain the tips generated in the authentication process. 7+ - -- Return values - - - - - - - - - - -

Type

-

Description

-

Authenticator

-

Authenticator object obtained.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - ``` - - -## Authenticator - -Provides an **Authenticator** object. - -### execute - -execute\(type: string, level: string, callback: AsyncCallback\): void - -Performs user authentication and returns the authentication result using an asynchronous callback. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Authentication type. Only FACE_ONLY is supported.

-

ALL is reserved and not supported by the current version.

-

level

-

string

-

Yes

-

Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).

-

Devices capable of 3D facial recognition support S3 and lower-level authentication.

-

Devices capable of 2D facial recognition support S2 and lower-level authentication.

-

callback

-

AsyncCallback<number>

-

No

-

Callback invoked to return the authentication result

-
- - Callback return values - - - - - - - - - - -

Type

-

Description

-

number

-

Authentication result. See AuthenticationResult.

-
- -- Example - - ``` - authenticator.execute("FACE_ONLY", "S2", (code)=>{ - if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }) - ``` - - -### execute - -execute\(type:string, level:string\): Promise - -Performs user authentication and returns the authentication result using a promise. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Authentication type. Only FACE_ONLY is supported.

-

ALL is reserved and not supported by the current version.

-

level

-

string

-

Yes

-

Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).

-

Devices capable of 3D facial recognition support S3 and lower-level authentication.

-

Devices capable of 2D facial recognition support S2 and lower-level authentication.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

Promise<number>

-

Promise used to return the authentication result. The number in the promise indicates the authentication result. See AuthenticationResult.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - authenticator.off("tip", tipCallback); - console.info("auth success"); - }).catch((code)=>{ - authenticator.off("tip", tipCallback); - console.error("auth fail, code = " + code); - }); - ``` - - -### cancel7+ - -cancel\(\): number - -Cancels the current authentication. - -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Whether the authentication is canceled. For details, see Result.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let cancelCode = authenticator.cancel(); - if (cancelCode == userIAM_userAuth.Result.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` - - -### checkAvailability7+ - -checkAvailability\(type: AuthType, level: SecureLevel\): number - -Checks whether the device supports the specified authentication type and security level. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Authentication type. Only FACE_ONLY is supported.

-

ALL is reserved and not supported by the current version.

-

level

-

string

-

Yes

-

Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).

-

Devices capable of 3D facial recognition support S3 and lower-level authentication.

-

Devices capable of 2D facial recognition support S2 and lower-level authentication.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Check result. For details, see CheckAvailabilityResult.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let checkCode = authenticator.checkAvailability("FACE_ONLY", "S2"); - if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) { - console.info("check auth support success"); - } else { - console.error("check auth support fail, code = " + checkCode); - } - ``` - - -### on7+ - -on\(type: "tip", callback: Callback\) : void; - -Subscribes to the events of the specified type. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. Currently, only tip is supported. An event is triggered when the authentication service sends a message to the caller.

-

callback

-

Callback<Tip>

-

Yes

-

Callback used to report the event of the specified type. Currently, only the tip event is supported.

-
- - -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode +") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - authenticator.on("tip", tipCallback); - ``` - - -### off7+ - -off\(type: "tip", callback?: Callback\) : void; - -Unsubscribes from the events of the specified type. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. Currently, only tip is supported.

-

callback

-

Callback<Tip>

-

No

-

Callback used to report the event of the specified type. Currently, only the tip event is supported. If this parameter is not specified, all callbacks corresponding to type will be canceled.

-
- - -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - // Unsubscribe from a specified callback. - authenticator.off("tip", tipCallback); - - // Unsubscribe from all callbacks. - authenticator.off("tip"); - ``` - - -## AuthenticationResult +## userIAM_userAuth.getAuthenticator(deprecated) + +getAuthenticator(): Authenticator + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8). + +Obtains an **Authenticator** object for user authentication. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Return value** +| Type | Description | +| ----------------------------------------- | ------------ | +| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| + +**Example** + ```js + let authenticator = userIAM_userAuth.getAuthenticator(); + ``` + +## Authenticator(deprecated) + +> **NOTE**
+> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8). + +Provides methods to manage an **Authenticator** object. + + +### execute(deprecated) + +execute(type: string, level: string, callback: AsyncCallback<number>): void + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). + +Performs user authentication. This method uses asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| callback | AsyncCallback<number> | No | Callback used to return the result. | + + Parameters returned in callback + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| + +**Example** + ```js + authenticator.execute("FACE_ONLY", "S2", (code)=>{ + if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); + }) + ``` + + +### execute(deprecated) + +execute(type:string, level:string): Promise<number> + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). + +Performs user authentication. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| + +**Return value** +| Type | Description | +| --------------------- | ------------------------------------------------------------ | +| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).| + +**Example** + +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); +}).catch((code)=>{ + console.error("auth fail, code = " + code); +}); +``` + +## AuthenticationResult(deprecated) + +> **NOTE**
+> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8). Enumerates the authentication results. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NO_SUPPORT

-

-1

-

The device does not support the current authentication mode.

-

SUCCESS

-

0

-

The authentication is successful.

-

COMPARE_FAILURE

-

1

-

The feature comparison failed.

-

CANCELED

-

2

-

The user cancels the authentication.

-

TIMEOUT

-

3

-

The authentication has timed out.

-

CAMERA_FAIL

-

4

-

The camera failed to start.

-

BUSY

-

5

-

The authentication service is not available. Try again later.

-

INVALID_PARAMETERS

-

6

-

The authentication parameters are invalid.

-

LOCKED

-

7

-

The user account is locked because the number of authentication failures has reached the threshold.

-

NOT_ENROLLED

-

8

-

No authentication credential is registered.

-

GENERAL_ERROR

-

100

-

Other errors.

-
- -## Tip7+ - -Defines the object of the tip generated during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

errorCode

-

number

-

Yes

-

Whether the tip is obtained successfully. For details, see Result.

-

tipEvent

-

number

-

Yes

-

Tip event. For details, see TipEvent. Currently, only RESULT and ACQUIRE are supported.

-

tipCode

-

number

-

Yes

-

Tip code.

-
  • If tipEvent is RESULT, the tip code provides the authentication result. For details, see AuthenticationResult.
  • If tipEvent is ACQUIRE, the tip code provides prompt information. For details, see TipCode.
-

tipInfo

-

string

-

Yes

-

Description of the tip code.

-
- -## Result7+ +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ------------------ | ------ | -------------------------- | +| NO_SUPPORT | -1 | The device does not support the current authentication mode.| +| SUCCESS | 0 | The authentication is successful. | +| COMPARE_FAILURE | 1 | The feature comparison failed. | +| CANCELED | 2 | The authentication was canceled by the user. | +| TIMEOUT | 3 | The authentication has timed out. | +| CAMERA_FAIL | 4 | The camera failed to start. | +| BUSY | 5 | The authentication service is not available. Try again later. | +| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. | +| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.| +| NOT_ENROLLED | 8 | No authentication credential is registered. | +| GENERAL_ERROR | 100 | Other errors. | + +## UserAuth8+ + +Provides methods to manage an **Authenticator** object. + +### constructor8+ + +constructor() + +A constructor used to create an **authenticator** object. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| [UserAuth](#userauth8) | **Authenticator** object obtained.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + ``` + +### getVersion8+ + +getVersion() : number + +Obtains the authentication executor version. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Authentication executor version obtained.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + let version = auth.getVersion(); + console.info("auth version = " + version); + ``` + +### getAvailableStatus8+ + +getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number + +Checks whether the authentication capability of the specified trust level is available. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------- | ---- | -------------------------- | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8).| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); + // Add the logic to be executed if the specified authentication type is supported. + } else { + console.error("check auth support fail, code = " + checkCode); + // Add the logic to be executed if the specified authentication type is not supported. + } + ``` + +### auth8+ + +auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array + +Performs user authentication. This method uses a callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | ------------------------ | +| challenge | Uint8Array | Yes | Challenge value, which can be null. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback used to return the result. | + +**Return value** + +| Type | Description | +| ---------- | ------------------------------------------------------------ | +| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8).| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } + }); + ``` + +### cancelAuth8+ + +cancelAuth(contextID : Uint8Array) : number + +Cancels an authentication. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ------------------------------------------ | +| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8).| + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| number | Whether the authentication is canceled.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // contextId can be obtained using auth(). In this example, it is defined here. + let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); + let cancelCode = auth.cancel(contextId); + if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); + } else { + console.error("cancel auth fail"); + } + ``` + +## IUserAuthCallback8+ + +Defines the object of the result returned by the callback during authentication. + +### onResult8+ + +onResult: (result : number, extraInfo : AuthResult) => void + +Obtains the authentication result. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------------------ | +| result | number | Yes | Authentication result obtained. For details, see [ResultCode](#resultcode8). | +| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| + + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } + }); + ``` + +### onAcquireInfo8+ + +onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void + +Obtains the tip code information during authentication. This function is optional. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------ | +| module | number | Yes | Type of the authentication executor. | +| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| extraInfo | any | Yes | Reserved field. | + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } + }); + ``` + +## AuthResult8+ + +Represents the authentication result object. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| token | Uint8Array | No | Identity authentication token. | +| remainTimes | number | No | Number of remaining authentication operations.| +| freezingTime | number | No | Time for which the authentication operation is frozen.| + +## ResultCode8+ Enumerates the operation results. - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SUCCESS

-

0

-

Successful

-

FAILED

-

1

-

Failed

-
- -## CheckAvailabilityResult7+ - -Enumerates the device authentication capability check results. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SUPPORTED

-

0

-

The device supports the specified authentication type and security level.

-

AUTH_TYPE_NOT_SUPPORT

-

1

-

The device does not support the specified authentication type.

-

SECURE_LEVEL_NOT_SUPPORT

-

2

-

The device does not support the specified authentication security level.

-

DISTRIBUTED_AUTH_NOT_SUPPORT

-

3

-

The device does not support distributed authentication.

-

NOT_ENROLLED

-

4

-

The device does not have the authentication credential.

-

PARAM_NUM_ERROR

-

5

-

The number of parameters is incorrect.

-
- -## TipEvent7+ - -Enumerates the tip events occurred during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

RESULT

-

1

-

Credential enrollment result or authentication result.

-

CANCEL

-

2

-

Credential enrollment or authentication canceled.

-

ACQUIRE

-

3

-

Tips generated in the credential enrollment or authentication process.

-

BUSY

-

4

-

Credential enrollment or authentication unavailable.

-

OUT_OF_MEM

-

5

-

Insufficient memory.

-

FACE_ID

-

6

-

Index of a face authentication credential.

-
- -## TipCode7+ - -Enumerates the tip codes generated during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

FACE_AUTH_TIP_TOO_BRIGHT

-

1

-

The obtained facial image is too bright due to high illumination.

-

FACE_AUTH_TIP_TOO_DARK

-

2

-

The obtained facial image is too dark due to low illumination.

-

FACE_AUTH_TIP_TOO_CLOSE

-

3

-

The face is too close to the device.

-

FACE_AUTH_TIP_TOO_FAR

-

4

-

The face is too far away from the device.

-

FACE_AUTH_TIP_TOO_HIGH

-

5

-

Only the upper part of the face is captured because the device is angled too high.

-

FACE_AUTH_TIP_TOO_LOW

-

6

-

Only the lower part of the face is captured because the device is angled too low.

-

FACE_AUTH_TIP_TOO_RIGHT

-

7

-

Only the right part of the face is captured because the device is deviated to the right.

-

FACE_AUTH_TIP_TOO_LEFT

-

8

-

Only the left part of the face is captured because the device is deviated to the left.

-

FACE_AUTH_TIP_TOO_MUCH_MOTION

-

9

-

The face moves too fast during facial information collection.

-

FACE_AUTH_TIP_POOR_GAZE

-

10

-

The face is not facing the camera.

-

FACE_AUTH_TIP_NOT_DETECTED

-

11

-

No face is detected.

-
+**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------------------- | ------ | -------------------- | +| SUCCESS | 0 | The operation is successful. | +| FAIL | 1 | The operation failed. | +| GENERAL_ERROR | 2 | A common operation error occurred. | +| CANCELED | 3 | The operation is canceled. | +| TIMEOUT | 4 | The operation timed out. | +| TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | +| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | +| BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | +| LOCKED | 9 | The authentication executor is locked. | +| NOT_ENROLLED | 10 | The user has not entered the authentication information.| + + +## FaceTips8+ + +Enumerates the tip codes used during the facial authentication process. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------------------------- | ------ | ------------------------------------ | +| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | +| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | +| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. | +| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. | +| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. | +| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | +| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is deviated to the right. | +| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is deviated to the left. | +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection.| +| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the camera. | +| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | + + +## FingerprintTips8+ + +Enumerates the tip codes used during the fingerprint authentication process. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| --------------------------------- | ------ | -------------------------------------------------- | +| FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | +| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| +| FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2 | The noise of the fingerprint image is too large to be processed. | +| FINGERPRINT_AUTH_TIP_PARTIAL | 3 | Incomplete fingerprint image is detected. | +| FINGERPRINT_AUTH_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to fast movement. | +| FINGERPRINT_AUTH_TIP_TOO_SLOW | 5 | Failed to obtain the fingerprint image because the finger seldom moves. | + + +## UserAuthType8+ + +Enumerates the identity authentication types. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------- | ------ | ---------- | +| FACE | 2 | Facial authentication.| +| FINGERPRINT | 4 | Fingerprint authentication.| + +## AuthTrustLevel8+ + +Enumerates the trust levels of the authentication result. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name| Default Value| Description | +| ---- | ------ | ------------------------- | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 8f24f6a17a..b4a031c8a8 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -5,7 +5,7 @@ > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. +This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **types** for checks of built-in object types. ## Modules to Import @@ -1614,20 +1614,20 @@ Decodes the input content asynchronously. ``` -## Types8+ +## types8+ ### constructor8+ constructor() -A constructor used to create a **Types** object. +A constructor used to create a **types** object. **System capability**: SystemCapability.Utils.Lang **Example** ``` - var type = new util.Types(); + var type = new util.types(); ``` @@ -1651,7 +1651,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isAnyArrayBuffer(new ArrayBuffer([])); ``` @@ -1678,7 +1678,7 @@ Checks whether the input value is of the **ArrayBufferView** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isArrayBufferView(new Int8Array([])); ``` @@ -1703,7 +1703,7 @@ Checks whether the input value is of the **arguments** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); function foo() { var result = that.isArgumentsObject(arguments); } @@ -1731,7 +1731,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isArrayBuffer(new ArrayBuffer([])); ``` @@ -1756,7 +1756,7 @@ Checks whether the input value is an asynchronous function. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isAsyncFunction(async function foo() {}); ``` @@ -1781,7 +1781,7 @@ Checks whether the input value is of the **Boolean** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isBooleanObject(new Boolean(true)); ``` @@ -1806,7 +1806,7 @@ Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isBoxedPrimitive(new Boolean(false)); ``` @@ -1831,7 +1831,7 @@ Checks whether the input value is of the **DataView** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const ab = new ArrayBuffer(20); var result = that.isDataView(new DataView(ab)); ``` @@ -1857,7 +1857,7 @@ Checks whether the input value is of the **Date** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isDate(new Date()); ``` @@ -1882,7 +1882,7 @@ Checks whether the input value is of the **native external** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const data = util.createExternalType(); var result = that.isExternal(data); ``` @@ -1908,7 +1908,7 @@ Checks whether the input value is of the **Float32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isFloat32Array(new Float32Array()); ``` @@ -1933,7 +1933,7 @@ Checks whether the input value is of the **Float64Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isFloat64Array(new Float64Array()); ``` @@ -1958,7 +1958,7 @@ Checks whether the input value is a generator function. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isGeneratorFunction(function* foo() {}); ``` @@ -1983,7 +1983,7 @@ Checks whether the input value is a generator object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); function* foo() {} const generator = foo(); var result = that.isGeneratorObject(generator); @@ -2010,7 +2010,7 @@ Checks whether the input value is of the **Int8Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt8Array(new Int8Array([])); ``` @@ -2035,7 +2035,7 @@ Checks whether the input value is of the **Int16Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt16Array(new Int16Array([])); ``` @@ -2060,7 +2060,7 @@ Checks whether the input value is of the **Int32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt32Array(new Int32Array([])); ``` @@ -2085,7 +2085,7 @@ Checks whether the input value is of the **Map** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isMap(new Map()); ``` @@ -2110,7 +2110,7 @@ Checks whether the input value is of the **MapIterator** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const map = new Map(); var result = that.isMapIterator(map.keys()); ``` @@ -2136,7 +2136,7 @@ Checks whether the input value is of the **Error** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isNativeError(new TypeError()); ``` @@ -2161,7 +2161,7 @@ Checks whether the input value is a number object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isNumberObject(new Number(0)); ``` @@ -2186,7 +2186,7 @@ Checks whether the input value is a promise. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isPromise(Promise.resolve(1)); ``` @@ -2211,7 +2211,7 @@ Checks whether the input value is a proxy. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const target = {}; const proxy = new Proxy(target, {}); var result = that.isProxy(proxy); @@ -2238,7 +2238,7 @@ Checks whether the input value is of the **RegExp** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isRegExp(new RegExp('abc')); ``` @@ -2263,7 +2263,7 @@ Checks whether the input value is of the **Set** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isSet(new Set()); ``` @@ -2288,7 +2288,7 @@ Checks whether the input value is of the **SetIterator** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const set = new Set(); var result = that.isSetIterator(set.keys()); ``` @@ -2314,7 +2314,7 @@ Checks whether the input value is a string object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isStringObject(new String('foo')); ``` @@ -2339,7 +2339,7 @@ Checks whether the input value is a symbol object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const symbols = Symbol('foo'); var result = that.isSymbolObject(Object(symbols)); ``` @@ -2367,7 +2367,7 @@ Checks whether the input value is of the **TypedArray** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isTypedArray(new Float64Array([])); ``` @@ -2392,7 +2392,7 @@ Checks whether the input value is of the **Uint8Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint8Array(new Uint8Array([])); ``` @@ -2417,7 +2417,7 @@ Checks whether the input value is of the **Uint8ClampedArray** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` @@ -2442,7 +2442,7 @@ Checks whether the input value is of the **Uint16Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint16Array(new Uint16Array([])); ``` @@ -2467,7 +2467,7 @@ Checks whether the input value is of the **Uint32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint32Array(new Uint32Array([])); ``` @@ -2492,7 +2492,7 @@ Checks whether the input value is of the **WeakMap** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isWeakMap(new WeakMap()); ``` @@ -2517,6 +2517,6 @@ Checks whether the input value is of the **WeakSet** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isWeakSet(new WeakSet()); ``` diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index ce4af8ba13..149fdc42e3 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -241,7 +241,8 @@ let result = vector.remove(2); ``` ### removeByRange -removeByRange(fromIndex: number, toIndex: number): void; + +removeByRange(fromIndex: number, toIndex: number): void Removes from this container all of the entries within a range, including the entry at the start position but not that at the end position. @@ -266,6 +267,7 @@ vector.removeByRange(2,6); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void @@ -303,8 +305,9 @@ vector.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, -thisArg?: Object): void; +thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -338,6 +341,7 @@ vector.forEach((value, index) => { ``` ### sort + sort(comparator?: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -369,6 +373,7 @@ vector.sort(); ``` ### subVector + subVector(fromIndex: number, toIndex: number): Vector<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **Vector** instance. @@ -401,6 +406,7 @@ let result2 = vector.subVector(2,6); ``` ### clear + clear(): void Clears all entries in this container and sets its length to **0**. @@ -417,6 +423,7 @@ vector.clear(); ``` ### clone + clone(): Vector<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. @@ -439,6 +446,7 @@ let result = vector.clone(); ``` ### getCapacity + getCapacity(): number Obtains the capacity of this container. @@ -461,6 +469,7 @@ let result = vector.getCapacity(); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -483,6 +492,7 @@ let result = vector.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entries). @@ -505,6 +515,7 @@ let result = vector.isEmpty(); ``` ### increaseCapacityTo + increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. @@ -528,6 +539,7 @@ vector.increaseCapacityTo(8); ``` ### trimToCurrentLength + trimToCurrentLength(): void Trims the capacity of this container into its current length. @@ -699,6 +711,7 @@ let result = vector.getIndexFrom(4, 3); ``` ### setLength + setLength(newSize: number): void Sets a new length for this container. @@ -722,6 +735,7 @@ vector.setLength(2); ``` ### get + get(index: number): T Obtains an entry at the specified position in this container. @@ -749,6 +763,7 @@ Obtains an entry at the specified position in this container. let result = vector.get(2); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 55c4189e30..1251c4b6d0 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -22,18 +22,18 @@ Triggers vibration with a specific duration. This API uses a promise to return t **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | duration | number | Yes| Vibration duration.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| duration | number | Yes | Vibration duration.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(1000).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -53,13 +53,13 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | duration | number | Yes| Vibration duration.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is triggered successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| duration | number | Yes | Vibration duration. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(1000,function(error){ if(error){ @@ -81,17 +81,17 @@ Triggers vibration with a specific effect. This API uses a promise to return the **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | effectId | [EffectId](#effectid) | Yes| String that indicates the vibration effect.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ------------- | +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -111,13 +111,13 @@ Triggers vibration with a specific effect. This API uses an asynchronous callbac **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | effectId | [EffectId](#effectid) | Yes| String that indicates the vibration effect.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is triggered successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ if(error){ @@ -139,17 +139,17 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes| Vibration mode to stop.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | --------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| -- Example +**Example** ``` vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -169,13 +169,13 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes| Vibration mode to stop.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is stopped successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | ----------------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully.| -- Example +**Example** ``` vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ if(error){ @@ -193,8 +193,8 @@ Describes the vibration effect. **System capability**: SystemCapability.Sensors.MiscDevice -| Name| Default Value| Description| -| -------- | -------- | -------- | +| Name | Default Value | Description | +| ------------------ | -------------------- | --------------- | | EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| @@ -204,7 +204,7 @@ Describes the vibration mode to stop. **System capability**: SystemCapability.Sensors.MiscDevice -| Name| Default Value| Description| -| -------- | -------- | -------- | -| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| +| Name | Default Value | Description | +| ------------------------- | -------- | ---------------------------------------- | +| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| | VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 5b51de9baa..d3d1781036 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -141,7 +141,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | Name | Readable| Writable | Type | Mandatory| Description | | -------- | --- | ---- | ----------------------- | ---- | --------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose bundle name is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -213,7 +213,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose bundle name is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -282,7 +282,7 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | ----------------------- | ---- | ----------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose user ID is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the user ID.| **Example** @@ -354,7 +354,7 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose user ID is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -423,7 +423,7 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | --------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose want is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the want.| **Example** @@ -495,7 +495,7 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose want is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -564,7 +564,7 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | --------------------- | ---- | --------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object to cancel. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -636,7 +636,13 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object to cancel.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 7ffb3babc8..1796e369ab 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -85,7 +85,7 @@ let ws = webSocket.createWebSocket(); ## WebSocket -Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#webSocketcreatewebsocket) to create a **WebSocket** object. +Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. ### connect diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 2070b5438c..c4d8d105f1 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -147,11 +147,11 @@ Enumerates the WLAN security types. | **Name**| **Default Value**| **Description**| | -------- | -------- | -------- | -| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type | -| WIFI_SEC_TYPE_OPEN | 1 | Open security type | -| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP) | -| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK) | -| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE) | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP)| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK)| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE)| ## wifi.addUntrustedConfig7+ @@ -182,11 +182,11 @@ Represents the WLAN configuration. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| | preSharedKey | string | Read only| Private key of the hotspot.| | isHiddenSsid | boolean | Read only| Whether to hide the network.| -| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type. | +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type| ## wifi.addUntrustedConfig7+ @@ -335,7 +335,7 @@ Represents the WLAN connection information. | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| +| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| | rssi | number | Read only| Signal strength of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN AP.| @@ -443,13 +443,13 @@ Represents IP information. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address. | -| gateway | number | Read only| Gateway. | -| netmask | number | Read only| Subnet mask. | -| primaryDns | number | Read only| IP address of the preferred DNS server. | -| secondDns | number | Read only| IP address of the alternate DNS server. | -| serverIp | number | Read only| IP address of the DHCP server. | -| leaseDuration | number | Read only| Lease duration of the IP address. | +| ipAddress | number | Read only| IP address| +| gateway | number | Read only| Gateway| +| netmask | number | Read only| Subnet mask| +| primaryDns | number | Read only| IP address of the preferred DNS server| +| secondDns | number | Read only| IP address of the alternate DNS server| +| serverIp | number | Read only| IP address of the DHCP server| +| leaseDuration | number | Read only| Lease duration of the IP address| ## wifi.getCountryCode7+ @@ -589,7 +589,7 @@ Represents the P2P device information. | deviceAddress | string | Read only| MAC address of the device.| | primaryDeviceType | string | Read only| Type of the primary device.| | deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| groupCapabilities | number | Read only| Group capabilities.| ## P2pDeviceStatus8+ @@ -1046,7 +1046,7 @@ Registers the hotspot state change events. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.AP + SystemCapability.Communication.WiFi.AP.Core - Parameters | **Name**| **Type**| **Mandatory**| **Description**| @@ -1073,7 +1073,7 @@ Unregisters the hotspot state change events. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.AP + SystemCapability.Communication.WiFi.AP.Core - Parameters | **Name**| **Type**| **Mandatory**| **Description**| @@ -1239,7 +1239,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[]](#WifiP2pDevice)> | 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[]](#WifiP2pDevice)> | No| Callback used to return the P2P peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index d3b1c26cd6..2e2e9394b2 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,7 @@ # WLAN > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -21,7 +21,7 @@ Enables the WLAN hotspot. ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | **Type**| **Description**| @@ -39,7 +39,7 @@ Disables the WLAN hotspot. ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | **Type**| **Description**| @@ -57,7 +57,7 @@ Obtains the supported power models. The method uses a promise to return the resu ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | Type| Description| @@ -86,7 +86,7 @@ Obtains the supported power models. The method uses an asynchronous callback to ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| @@ -104,7 +104,7 @@ Obtains the power model. The method uses a promise to return the result. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | Type| Description| @@ -122,7 +122,7 @@ Obtains the power model. The method uses an asynchronous callback to return the ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| @@ -140,7 +140,7 @@ setPowerModel(model: PowerModel) : boolean; ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index c3ec8f7fb3..c8ae2e39fd 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -160,12 +160,14 @@ Describes the color gamut mode. | DEFAULT | 0 | Default color gamut mode.| | WIDE_GAMUT | 1 | Wide color gamut mode. | -## window.create7 +## window.create7+ create(id: string, type: WindowType, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. +This API is discarded since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. + **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters @@ -191,12 +193,14 @@ Creates a subwindow. This API uses an asynchronous callback to return the result }); ``` -## window.create7 +## window.create7+ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. +This API is discarded since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. + **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters @@ -229,18 +233,18 @@ Creates a subwindow. This API uses a promise to return the result. create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a system window when the context is [ServiceExtensionContext](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-service-extension-context.md). This API uses an asynchronous callback to return the result. +Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context, which is the base class of **ServiceExtensionContext**.| - | id | string | Yes | Window ID. | - | type | [WindowType](#windowtype) | Yes | Window type. | - | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the system window created. | + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------- | ---- | ---------------------- | + | ctx | [Context](js-apis-service-extension-context.md) | Yes | Current application context. | + | id | string | Yes | Window ID. | + | type | [WindowType](#windowtype) | Yes | Window type. | + | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the system window created.| - Example @@ -261,17 +265,17 @@ Creates a system window when the context is [ServiceExtensionContext](https://gi create(ctx: Context, id: string, type: WindowType): Promise<Window> -Creates a system window when the context is [ServiceExtensionContext](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-service-extension-context.md). This API uses a promise to return the result. +Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters - | Name| Type | Mandatory| Description | - | ------ | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context, which is the base class of **ServiceExtensionContext**.| - | id | string | Yes | Window ID. | - | type | [WindowType](#windowtype) | Yes | Window type. | + | Name| Type | Mandatory| Description | + | ------ | ----------------------------------------------- | ---- | -------------------- | + | ctx | [Context](js-apis-service-extension-context.md) | Yes | Current application context.| + | id | string | Yes | Window ID. | + | type | [WindowType](#windowtype) | Yes | Window type. | - Return value @@ -419,10 +423,10 @@ Obtains the top window of the current application. This API uses an asynchronous - Parameters - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context. | - | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | + | ctx | [Context](js-apis-Context.md) | Yes | Current application context. | + | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | - Example @@ -448,9 +452,9 @@ Obtains the top window of the current application. This API uses a promise to re - Parameters - | Name| Type | Mandatory| Description | - | ------ | ------------------------------------------------------------ | ---- | -------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context.| + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ------------------------------------------------------------ | + | ctx | [Context](js-apis-Context.md) | Yes | Current application context. | - Return value @@ -523,7 +527,7 @@ This is a system API and cannot be called by third-party applications. ## Window -In the following API examples, you must use [getTopWindow()](#window-gettopwindow), [create()](#window-create), or [find()](#window-find) to obtain a **Window** instance and then call a method in this instance. +In the following API examples, you must use [getTopWindow()](#window-gettopwindow), [create()](#windowcreate7), or [find()](#window-find) to obtain a **Window** instance and then call a method in this instance. ### hide7+ diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index b0c4df2c83..65ad4b6437 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -329,6 +329,7 @@ that.parse(options); Defines the XML parsing options. + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.| @@ -337,7 +338,6 @@ Defines the XML parsing options. | attributeValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **attributeValue**.| | tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=> boolean | No| Callback used to return **tokenValue**.| - ## ParseInfo Provides APIs to manage the parsed XML information. diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 0a6cd0200e..f1435417e6 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -3,7 +3,11 @@ ## Constraints None ## Modules to Import -import zlib from '@ohos.zlib' + +```javascript +import zlib from '@ohos.zlib'; +``` + ## zlib.zipFile zipFile(inFile:string, outFile:string, options: Options): Promise; Zips a file. This API uses a promise to return the result. @@ -121,7 +125,7 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ## options -| Name | | +| Name | Description | | --------------------------- | ------------------------------------------------------------ | | level?: CompressLeve | See [zip.CompressLevel](#zip.CompressLevel).| | memLevel?: MemLevel | See [zip.MemLevel](#zip.MemLevel) | @@ -129,8 +133,9 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ## zip.MemLevel -| MEM_LEVEL_MIN | Minimum memory used by the **zip** API during compression.| +| Name | Description | | ----------------- | -------------------------------- | +| MEM_LEVEL_MIN | Minimum memory used by the **zip** API during compression.| | MEM_LEVEL_MAX | Maximum memory used by the **zip** API during compression.| | MEM_LEVEL_DEFAULT | Default memory used by the **zip** API during compression.| @@ -150,7 +155,7 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { | COMPRESS_STRATEGY_DEFAULT_STRATEGY : 0 | Default compression strategy. | | COMPRESS_STRATEGY_FILTERED : 1 | Filtered compression strategy.| | COMPRESS_STRATEGY_HUFFMAN_ONLY : 2 | Huffman coding compression strategy. | -| OMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | +| COMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | | COMPRESS_STRATEGY_FIXED : 4 | Fixed compression strategy. | ## zip.ErrorCode -- GitLab